I started using Styled Components for my next js app and wondered how or whether to use styled components for global styles. Thought of sharing that in Q n A format.
To create global styles we can use createGlobalStyle
function. For next.js
project, you can do that in _app.js
or _app.tsx
file, depending on whether you are using typescript.
import type { AppProps } from "next/app";
import { createGlobalStyle } from "styled-components";
import Header from "@/components/Header";
const GlobalStyles = createGlobalStyle`
html,
body {
padding: 0;
margin: 0;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
`;
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<>
<GlobalStyles />
<Header></Header>
<Component {...pageProps} />
</>
);
}
Of course, if you have more global styles you can export the GlobalStyles
from other file, say globalStyle.js
.
But then there is nothing out there that stops you from using CSS or SCSS for your global styles. You can always import the .css
or .scss
or any other supported CSS preprocessor file types as you would normally do.
import '@/styles/global.scss'
And this would work perfectly fine with your Styled Components as well. Though there is a little advantage you get by using createGlobalStyle
. You can use all SCSS features without having to add SCSS dependency in your project. And a little drawback is that the auto-complete features of the ide don't work as well with styled-components as they do with .css
and .scss
files.