Use CSS to style Next.js components

How to style React components in Next.js?

How do we style React components in Next.js?

We have a lot of freedom because we can use any library we like.

But Next.js comes withstyled-jsxBuilt-in, because this is a library built by the same person who worked on Next.js.

It is a very cool library that provides us with CSS within the scope, which is very useful for maintainability, because CSS only affects the applied components.

I think this is a good way to write CSS without having to apply other libraries or preprocessors that add complexity.

To add CSS to the React component in Next.js, we insert it into a fragment of JSX that starts with

<style jsx>{`

and

`}</style>

In this weird code block, we have written ordinary CSS, just like we are in.cssfile:

<style jsx>{`
  h1 {
    font-size: 3rem;
  }
`}</style>

You can write it in JSX as follows:

const Index = () => (
  <div>
		<h1>Home page</h1>
	<span style="color:#f92672">&lt;</span><span style="color:#a6e22e">style</span> <span style="color:#a6e22e">jsx</span><span style="color:#f92672">&gt;</span>{<span style="color:#e6db74">`

h1 { font-size: 3rem; } `}</style> </div> )

export default Index

Inside the block, we can use interpolation to dynamically change the value. For example, here we assumesizeprop is passed by the parent component, we arestyled-jsxBlockage:

const Index = props => (
  <div>
		<h1>Home page</h1>
	<span style="color:#f92672">&lt;</span><span style="color:#a6e22e">style</span> <span style="color:#a6e22e">jsx</span><span style="color:#f92672">&gt;</span>{<span style="color:#e6db74">`

h1 { font-size: ${props.size}rem; } `}</style> </div> )

If you want to apply some CSS globally instead of applying it to a component, you can addglobalKeywordstylelabel:

<style jsx global>{`
body {
  margin: 0;
}
`}</style>

If you want to import an external CSS file in the Next.js component, you must install it first@zeit/next-css:

npm install @zeit/next-css

Then create a configuration file in the root directory of the project, namednext.config.js, The content is as follows:

const withCSS = require('@zeit/next-css')
module.exports = withCSS()

After restarting the Next application, you can now import CSS as you would normally use JavaScript libraries or components:

import '../style.css'

You can also use@zeit/next-sassLibrary.

Download mine for freeNext.js manual


More tutorials next: