Introduction
Follow this guide to setup style components in react components
Styled-components makes it simple to style your components with CSS by using javascript code. It also makes it simple to design a theme for your entire project.
Table Of Content
- Create Nextjs Project
- Add Styled-components Library
- [optional] Styled Components Babel Plugin
- [optional] SSR Stylesheet Rehydration
- [optional] Absolute imports & Module Path Aliases
Create Nextjs Project
Create Nextjs easily by using create-next-app
by running the command below replace with your project name
yarn create next-app <project> --ts
or if you need eslint run the command below instead, replace with your project name
yarn create next-app <project> --ts --eslint
learn more on getting started with Nuxtjs
Add Styled-components Library
In your project root directory run the command below to add styled-components library
yarn add styled-components && yarn add -D @types/styled-components
Use globalStyle
, to share styles across all of your pages, for example if you would like;
- Setting a font-family for all your typography
- Setting the background color on every page
create a folder /layout
with file Default.tsx
inside, then add the following:
import { createGlobalStyle } from "styled-components";
export const GlobalStyle = createGlobalStyle`
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
}
p {
color: red;
}
// anything else you would like to include
`;
export function LayoutDefault({ children }: { children: any }) {
return (
<>
<GlobalStyle />
{children}
</>
);
}
Inside the GlobalStyle variable is where you define all your global styles.
In this example, we simply set the font family, link color, and paragraph color for every page LayoutDefault is used
This isn’t going to apply the styles to the project yet.
Now we need to use that file to apply the global styles to the project.
Modify index.tsx
file in the /pages
folder, import the LayoutDefault component and wrap the returned React element in the Home function with LayoutDefault.
import styled from "styled-components";
import LayoutDefault from "../layout/Default";
const StyledHeading = styled.h1`
color: pink;
`;
export default function Home() {
return (
<LayoutDefault>
<StyledHeading>Title</StyledHeading>
<p>hello</p>
</LayoutDefault>
);
};
[optional] Styled Components Babel Plugin
You need to add the babel styled components plugin, if you want any of the following features
- Smaller bundles
- Server-side rendering compatibility
- Better debugging
- Minification
- Dead code elimination learn more about
yarn add -D babel-plugin-styled-components
Create a file .babelrc
at the root of your project with the following:
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
}
[optional] SSR Stylesheet Rehydration
ServerStyleSheet is created by Styled-Components. Any styles located in any of the components inside of our are retrieved from this stylesheet. Later, this is passed into our HTML template.
create file _document.tsx
in the /pages
directory and add the following
import Document, { DocumentContext, DocumentInitialProps } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
export default class MyDocument extends Document {
static async getInitialProps(
ctx: DocumentContext
): Promise<DocumentInitialProps> {
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();
}
}
}
[optional] Absolute imports & Module Path Aliases
If you've ever imported deep components and they appear with a module path alias like this:../../../../DeepComponent, with Module Path Alias you can import them like this instead components/path/DeepComponent
learn about absolut imports and module path aliases
{
"compilerOptions": {
"baseUrl": "."
}
}
Now in /pages/index.tsx
you can do this instead of that:
// This
import LayoutDefault from "layout/Default";
// That
import LayoutDefault from "../layout/Default";
Top comments (0)