This is what ThemeProvider for!
Your stylized components have access to special theme support when they interpolate a function:
const Button = styled.button` background: ${props => props.theme.primary}; `
This <Button /> component will now dynamically respond to a theme defined by ThemeProvider . How do you define a topic? Pass any object to theme prop ThemeProvider :
const theme = { primary: 'palevioletred', }; <ThemeProvider theme={theme}> <Button>I'm now palevioletred!</Button> </ThemeProvider>
We provide a theme for your styled components through context , that is, regardless of how many nodes or DOM nodes are between the component and ThemeProvider, it will work in exactly the same way:
const theme = { primary: 'palevioletred', }; <ThemeProvider theme={theme}> <div> <SidebarContainer> <Sidebar> <Button>I'm still palevioletred!</Button> </Sidebar> </SidebarContainer> </div> </ThemeProvider>
This means that you can wrap your entire application in one ThemeProvider , and all your stylized components will get this theme. You can dynamically change this property to change between a dark and dark theme!
Your application can have as many or less ThemeProvider as you want. In most applications, you only need one to wrap the entire application, but for part of your application to be light and some other part of the dark theme, you would simply ThemeProvider them in two ThemeProvider , which have different themes:
const darkTheme = { primary: 'black', }; const lightTheme = { primary: 'white', }; <div> <ThemeProvider theme={lightTheme}> <Main /> </ThemeProvider> <ThemeProvider theme={darkTheme}> <Sidebar /> </ThemeProvider> </div>
Any style anywhere inside the Main will now be light, and any style anywhere inside the Sidebar will be dark. They adapt depending on what area of ββthe application they are in, and you do not need to do anything to make this happen! π
I recommend that you familiarize yourself with our topic documents , as stylized components were built with this in mind.
One of the big pain points of styles in JS before stylized components existed was that previous libraries did very well encapsulating and layout styles, but none of them had the proper support. If you want to know more about other aspects of the pain that we had with existing libraries, I would advise you to watch my conversation in ReactNL , where I released stylized text, components. (note: the first appearance of stylized components is ~ 25 minutes, do not be surprised!)