Search code examples
javascriptreactjsstyled-componentsthemeprovider

Using ThemeProvider in separate style sheets


I've been attempting to integrate the ThemeProvider from styled-components into an existing project. But run into the error below when accessing the theme's items in a style sheet:

TypeError: Cannot read properties of undefined (reading 'sidebarImage')
  10 |     315deg,
  11 |     ${p => p.bgColor1} 0%,
  12 |     ${p => p.bgColor2} 74%),
> 13 |     url(${(props) => props.theme.images.sidebarImage});
     | ^  14 |     
  15 | background-size: cover;
  16 | background-repeat: no-repeat;

After fiddling around a bit I found the source of the issue. In the tutorial I've been following, all styled components are defined in the same file as the component that uses it (i.e. Container is defined in App.js). In the project I'm working on all styled components are defined in separate style sheets (so Container would be in App.styles.js which is then imported to App.js).

Moving the styled components from App.styles.js to App.js fixes the issue. However would it be possible to give the style sheets access to the Themeprovider?


Solution

  • Once I got the source of the issue It was easy to solve. Using the answer here I've worked up this solution (though there might be a better approach).

    import { useTheme } from "styled-components";
    
    ...
    
    const Sidebar = (props) => {
        const theme = useTheme();
    
        ...
    
        return (
            <s.SidebarContainer theme={theme}
                                isSidebarOpen={isSidebarOpen}>
                
                <s.SidebarHeader theme={theme}>
                    {sidebarHeader}
                </s.SidebarHeader>
            </s.SidebarContainer>
        )