Questions
How do you do styling in Next.js?
The Scenario
You are a frontend engineer at a social media company. You are building a new component that needs to have some custom styles.
You are not sure which of the different ways to do styling in Next.js you should use.
The Challenge
Explain the different ways to do styling in Next.js. What are the pros and cons of each approach, and which one would you choose for this use case?
A junior engineer might just use a global stylesheet for everything. This would not be a very scalable or maintainable solution.
A senior engineer would know that there are several different ways to do styling in Next.js. They would be able to explain the pros and cons of each approach and would have a clear recommendation for which one to use in a given situation.
Step 1: Understand the Different Ways to Do Styling
| Method | Description |
|---|---|
| Global Styles | A global stylesheet that is applied to the entire application. |
| CSS Modules | A CSS file in which all class names and animation names are scoped locally by default. |
| Styled-JSX | A CSS-in-JS library that is built into Next.js. |
| CSS-in-JS Libraries | Libraries like Emotion and Styled Components. |
Step 2: Choose the Right Tool for the Job
| Use Case | Recommended Method |
|---|---|
| A simple application with a few pages | Global Styles |
| A component library | CSS Modules |
| A large application with many components | CSS-in-JS Libraries |
For our use case, we should use CSS Modules. This is because we are building a new component that needs to have its own custom styles, and we want to make sure that the styles are scoped locally to the component.
Step 3: Code Examples
Here are some code examples that show the difference between the different approaches:
Global Styles:
// pages/_app.js
import '../styles.css'
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}CSS Modules:
// components/MyComponent.module.css
.my-class {
color: red;
}
// components/MyComponent.js
import styles from './MyComponent.module.css'
export default function MyComponent() {
return <div className={styles['my-class']}>Hello, world!</div>
}Styled-JSX:
export default function MyComponent() {
return (
<div>
<p>Hello, world!</p>
<style jsx>{`
p {
color: red;
}
`}</style>
</div>
);
} Practice Question
You are building a component library and you want to make sure that the styles are scoped locally to each component. Which of the following would be the most appropriate?