June 02, 2020
If you’ve opted to use styled-components as a solution for managing your CSS, you’ll quickly ask yourself:
The Styled Components library is all about styling individual components. So how can you apply styles globally to an application?
For example, you might want to:
In this post, I’ll dive into exactly how you can achieve this with the createGlobalStyle function.
Please note: This solution is only applicable to web, so this won’t work for react-native!
Ready? Let’s do it.
The first step is to create a file that contains all your global styles.
Inside your src/
folder, add a file called globalStyles.js
.
Here, we’ll use the createGlobalStyle
function from styled-components and add some global styles:
// globalStyles.jsimport { createGlobalStyle } from 'styled-components';const GlobalStyle = createGlobalStyle`body {margin: 0;padding: 0;background: teal;font-family: Open-Sans, Helvetica, Sans-Serif;}`;export default GlobalStyle;
Inside the GlobalStyle variable is where you define all your global styles.
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 application.
Find your component which is at the top of your React tree.
In many react applications, that’s typically the App.js
file.
Here, import your GlobalStyle component and place it inside the the top of your React tree:
// App.jsimport React, { Fragment } from 'react';import GlobalStyle from './theme/globalStyle';import Content from './components/Content';function App() {return (<Fragment><GlobalStyle /><Content /></Fragment>);}export default App;
In the above code example, <Content />
is a component that contains all the other components for the application.
This is just an example, and you might structure the top of your React tree differently, like this:
// App.jsimport React, { Fragment } from 'react';import GlobalStyle from './theme/globalStyle';import Wrapper from './components/Wrapper';import Nav from './components/Nav';import Content from './components/Content';function App() {return (<Fragment><GlobalStyle /><Wrapper><Nav /><Content /></Wrapper></Fragment>);}export default App;
The important thing to remember is to place the GlobalStyle
component as a sibling component to your main application component(s).
And that’s it!
Global styling is now all set up with Styled Components.
Levelling up your React and CSS skills in 2021 is a great idea. Here's why: