How to configure Styled Components in Next.js
Requirement:
Configure Styled Components in Next.js
About Next.JS
Next.JS is a front-end framework of ReactJS, open source and created by Vercel (formerly known as ZEIT). It has a lot of cool features, including: Server Side Render (SSR), Static Site Generation (SSG), TypeScript support, image & font optimization, and much more!
What are Styled Components
Styled Components are CSS-in-JS tools, which allows us to write CSS in a componentized way, without worrying about errors and conflicts with class names. In addition, thier syntax are very similar to SCSS, for example, automatic nesting. You can check all the features at official documentation.
Start Building
Start by creating a new project with the following command:
npx create-next-app my-app
# or
yarn create next-app my-app
Enter to the project folder and install Style Components:
npm i styled-components
# or
yarn add styled-components
Inside the folder pages
, create a file with the name _document.js
, it will be needed to inject the styles in the server-side rendering:
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
Now we need to install and configure the babel plugin to add Styled Components support in SSR:
npm i -D babel-plugin-styled-components
# or
yarn add -D babel-plugin-styled-components
In the project root, create a file named .babelrc
:
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}
Let's do a little test to see if it's working properly. To do this, replace the entire contents of the file pages/index.js
with this one:
import styled from "styled-components";
export default function Home() {
const Wrapper = styled.section`
padding: 4em;
background: blueviolet;
`;
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: azure;
`;
return (
<Wrapper>
<Title>
Hello World!
</Title>
</Wrapper>
);
}
Run the command npm run dev
or yarn dev
and open it http://localhost:3000 in your browser. After the page loads, disable JavaScript in your browser and reload the page. If everything is ok, the styling will be get maintained.
That's it! After all these steps, Styled Components is ready to be used together with Next.JS
Thanks!