sections/api/helpers/create-global-style.mdx
import Code from 'components/Code' import Table, { Row, Column } from 'components/Table'
createGlobalStyle | v4 | web-onlyA helper function to generate a special StyledComponent that handles global styles. Normally, styled components are automatically scoped to a local CSS class and therefore isolated from other components. In the case of createGlobalStyle, this limitation is removed and things like CSS resets or base stylesheets can be applied.
Returns a StyledComponent that does not accept children. Place it at the top of your React tree and the global styles will be injected when the component is "rendered".
import { createGlobalStyle } from 'styled-components'
const GlobalStyle = createGlobalStyle<{ $whiteColor?: boolean; }>`
body {
color: ${props => (props.$whiteColor ? 'white' : 'black')};
}
`
// later in your app
<React.Fragment>
<GlobalStyle $whiteColor />
<Navigation />
</React.Fragment>
Since the GlobalStyle component is a StyledComponent, that means it also has access to theming from the <ThemeProvider> component if provided.
import { createGlobalStyle, ThemeProvider } from 'styled-components'
const GlobalStyle = createGlobalStyle<{ $whiteColor?: boolean; }>`
body {
color: ${props => (props.$whiteColor ? 'white' : 'black')};
font-family: ${props => props.theme.fontFamily};
}
`
// later in your app
<ThemeProvider theme={{ fontFamily: 'Helvetica Neue' }}>
<React.Fragment>
<Navigation />
<GlobalStyle $whiteColor />
</React.Fragment>
</ThemeProvider>