Theming
βοΈ Edit this pageTheming is included in the @emotion/react
package.
Add ThemeProvider
to the top level of your app and access the theme with props.theme
in a styled component or provide a function that accepts the theme as the css prop.
Table of Contents
Examples
css prop
styled
useTheme hook
API
ThemeProvider: React.ComponentType
A React component that passes the theme object down the component tree via context. Additional ThemeProvider
components can be added deeper in the tree to override the original theme. The theme object will be merged into its ancestor as if by Object.assign
. If a function is passed instead of an object it will be called with the ancestor theme and the result will be the new theme.
Accepts:
children
: React.Nodetheme
: Object|Object => Object - An object or function that provides an object.
import * as React from 'react'
import styled from '@emotion/styled'
import { ThemeProvider, withTheme } from '@emotion/react'
// object-style theme
const theme = {
backgroundColor: 'green',
color: 'red'
}
// function-style theme; note that if multiple <ThemeProvider> are used,
// the parent theme will be passed as a function argument
const adjustedTheme = ancestorTheme => ({ ...ancestorTheme, color: 'blue' })
class Container extends React.Component {
render() {
return (
<ThemeProvider theme={theme}>
<ThemeProvider theme={adjustedTheme}>
<Text>Boom shaka laka!</Text>
</ThemeProvider>
</ThemeProvider>
)
}
}
Note:
Make sure to hoist your theme out of render otherwise you may have performance problems.
withTheme(component: React.ComponentType): React.ComponentType
A higher-order component that provides the current theme as a prop to the wrapped child and listens for changes. If the theme is updated, the child component will be re-rendered accordingly.
import * as PropTypes from 'prop-types'
import * as React from 'react'
import { withTheme } from '@emotion/react'
class TellMeTheColor extends React.Component {
render() {
return <div>The color is {this.props.theme.color}.</div>
}
}
TellMeTheColor.propTypes = {
theme: PropTypes.shape({
color: PropTypes.string
})
}
const TellMeTheColorWithTheme = withTheme(TellMeTheColor)
useTheme
A React hook that provides the current theme as its value. If the theme is updated, the child component will be re-rendered accordingly.
Credits
Thanks goes to the styled-components team and their contributors who designed this API.