Setting up Styled Components in Next.js

In this article, I want to show you how to set up Styled Components in Next.js. Unlike the case in React, we cannot use Styled Components in Next.js by just installing it.

Installing Styled Components

After launching a Next.js project using the “create-next-app” , you need to install the followings:

npm install styled-components
npm install -D @types/styled-components
npm install -D babel-plugin-styled-components
npm install -D typescript

After installing the libraries, dependencies and devDependecies in the “package.json” file will be looked like this:


Create .babelrc file

Next step is to create a “.babelrc” file in the directory where the package.json is located. In the “.babelrc” file, we set the styled-components configuration.

.babelrc

{
“presets”: [“next/babel”],
“plugins”: [
[
“styled-components”,
{
“ssr”: true,
“displayName”: “preprocess”: false
}
]
]
}

Create _app.tsx file

After creating a Next.js project, there is an “_app.js” file inside the “pages” directory. Change the file name to “_app.tsx” and rewrite the content as the following. The role of the “_app.tsx” file is the same as the original “_app.js” file.

On the third line, “createGlobalStyle” is imported. This is equivalent to the “global.css” file in the “styles” directory. On line five, we use the “createGlobalStyle” and put the CSS applying globally inside the backticks. In this example, we just set the margin:0 and padding:0.


._app.tsx

import React, { useEffect } from “react”;
import { AppProps } from “next/app”;
import { createGlobalStyle } from “styled-components”;

const GlobalStyle = createGlobalStyle`
body {
padding: 0;
margin: 0;
`;

const CustomApp = ({ Component, pageProps
}: AppProps): JSX.Element => {

useEffect(() => {
const jssStyles: Element | null =
document.querySelector(“#jss-server-side”);
if (jssStyles) {
jssStyles.parentElement?.removeChild(jssStyles);
}
}, []);

return (
< div>
<GlobalStyle />
<Component {pageProps} />
< div>
);
};

export default CustomApp;


Once the GlobalStyle is defined in the “_app.tsx”, you don’t need the “globals.css” inside the “styles” directory.

You can also delete the “Home.module.css”, since it is only used in the first default Next.js project page. Now you can use Styled components in your Next.js project. Happy coding.