How To Create Global Styles With Styled Components

React

24/06/2021


There are times where you want to style your React application globally and not each component individually. For this, we can make use of the createGlobalStyle API.

createGlobalStyle is a web-only API, i.e. it won't work in React Native.

Step 1: Create a global styles file

Create a file that contains your global styles, e.g. global.css.js.

JSX
import { createGlobalStyle } from 'styled-components'
export default createGlobalStyle`
body {
margin: 0;
padding: 0;
color: ${props => (props.darkMode ? 'white' : 'black')};
}
`

You can apply string interpolations as expected. However, be aware that createGlobalStyle returns a component that doesn't accept any children. 🧒

Step 2: Add it to your React tree

At the root of your application, add the global styles component at the same level or deeper than your content (in this example App).

JSX
import React from 'react'
import ReactDOM from 'react-dom'
import { ThemeProvider } from 'styled-components'
import { App } from './App'
import { theme } from './theme'
import GlobalCSS from './global.css'
ReactDOM.render(
<ThemeProvider theme={theme}>
<GlobalCSS />
<App />
</ThemeProvider>, document.getElementById('root')
)

Since GlobalCSS is a styled component 💅, it can also take advantage of ThemeProvider.


WRITTEN BY

Code and stuff