How do we style React components in Next.js?
We have a lot of freedom, because we can use whatever library we prefer.
But Next.js comes with styled-jsx
built-in, because that’s a library built by the same people working on Next.js.
And it’s a pretty cool library that provides us scoped CSS, which is great for maintainability because the CSS is only affecting the component it’s applied to.
I think this is a great approach at writing CSS, without the need to apply additional libraries or preprocessors that add complexity.
To add CSS to a React component in Next.js we insert it inside a snippet in the JSX, which start with
<style jsx>{`
and ends with
`}</style>
Inside this weird blocks we write plain CSS, as we’d do in a .css
file:
<style jsx>{`
h1 {
font-size: 3rem;
}
`}</style>
You write it inside the JSX, like this:
const Index = () => (
<div>
<h1>Home page</h1>
<style jsx>{`
h1 {
font-size: 3rem;
}
`}</style>
</div>
)
export default Index
Inside the block we can use interpolation to dynamically change the values. For example here we assume a size
prop is being passed by the parent component, and we use it in the styled-jsx
block:
const Index = props => (
<div>
<h1>Home page</h1>
<style jsx>{`
h1 {
font-size: ${props.size}rem;
}
`}</style>
</div>
)
If you want to apply some CSS globally, not scoped to a component, you add the global
keyword to the style
tag:
<style jsx global>{`
body {
margin: 0;
}
`}</style>
If you want to import an external CSS file in a Next.js component, you have to first install @zeit/next-css
:
npm install @zeit/next-css
and then create a configuration file in the root of the project, called next.config.js
, with this content:
const withCSS = require('@zeit/next-css')
module.exports = withCSS()
After restarting the Next app, you can now import CSS like you normally do with JavaScript libraries or components:
import '../style.css'
You can also import a SASS file directly, using the @zeit/next-sass
library instead.
Download my free Next.js Handbook
More next tutorials:
- Getting started with Next.js
- Next.js vs Gatsby vs create-react-app
- How to install Next.js
- Linking two pages in Next.js using Link
- Dynamic content in Next.js with the router
- Feed data to a Next.js component using getInitialProps
- Styling Next.js components using CSS
- Prefetching content in Next.js
- Using the router to detect the active link in Next.js
- View source to confirm SSR is working in Next.js
- Next.js: populate the head tag with custom tags
- Deploying a Next.js application on Now
- Next.js: run code only on the server side or client side in Next.js
- Deploying a Next.js app in production
- How to analyze the Next.js app bundles
- Lazy loading modules in Next.js
- Adding a wrapper component to your Next.js app
- The icons added by Next.js to your app
- The Next.js App Bundles
- How to use the Next.js Router
- How to use Next.js API Routes
- How to get cookies server-side in a Next.js app
- How to change a Next.js app port