The className attribute in Next.js is used the same way as it is in React since Next.js is a framework built on top of React. It's a way to apply CSS classes to your JSX elements.
In JavaScript, class is a reserved keyword, so className is used instead when you want to specify a CSS class. The class names defined in className can be used to apply styles defined in your CSS or CSS-in-JS solutions.
Here's an example of how to use it:
function HomePage() {
return <div className="container">Hello, Next.js!</div>;
}
In the above example, the div element will have a class of "container". You can then use this class in your CSS to apply specific styles:
.container {
margin: 0 auto;
width: 50%;
padding: 20px;
}
Next.js supports CSS Modules out of the box, which automatically generates unique class names. This is useful for avoiding naming collisions in the global scope. When using CSS Modules, you can import the CSS file and refer to the classes like so:
import styles from './HomePage.module.css';
function HomePage() {
return <div className={styles.container}>Hello, Next.js!</div>;
}
In the above example, HomePage.module.css is a CSS file that is located in the same directory as the JavaScript file. The CSS file might look like this:
.container {
margin: 0 auto;
width: 50%;
padding: 20px;
}
In this case, the styles.container expression in the JSX code will resolve to a string that Next.js generates. This string will be a unique class name that matches the one in the generated CSS.