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:
- Set a font-family for all your typography
- Set the background color on every page
- Override some browser default styling
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.
Step 1: Create a global styles file
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.js
import { 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.
Step 2: Place GlobalStyle at the top of your React tree
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.js
import 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.js
import 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.
Download The Free Styled Components Cheat Sheet
I'm currently working on a styled components 1-pager. Grab it here.
Top comments (0)