Search code examples
reactjsnext.jsstyled-components

How can I access themeprovider/styled-components styles from render in React/NextJS


I have my code setup working like this....

_app.js

<ThemeProvider theme={clientGroupTheme}>
    <GlobalStyles />
    <Layout>
      <Component {...this.props} />
    </Layout>
</ThemeProvider>

someComponent.js

import { createGlobalStyle } from 'styled-components'
export const LoginMenuStyles = createGlobalStyle`
    .exampleClass {
         color:${(props) => props.theme.secondaryColor};
    }`

class LoginMenu extends React.Component {
    render() {
        return ( <>
                <div className="exampleClass">Test</div>
                <PassColorComponent myColor={${(props) => props.theme.secondaryColor}} /> //This
            </>
        )
    }
}

Basically I want to pass that same color value as a prop (//This). It works fine in the styled-component class but I can get it to work in the render method and pass to that component. Is it possible? am I close? Thanks


Solution

  • I think 'withTheme' higher-order component is what you are looking for.

    import { withTheme } from 'styled-components'
    
    
    class LoginMenu extends React.Component {
        render() {
            return ( <>
                    <div className="exampleClass">Test</div>
                    <PassColorComponent myColor={this.props.theme.secondaryColor} />
                </>
            )
        }
    }
    
    export default withTheme(LoginMenu);
    

    don't forget to wrap the component at export inside the withTheme component (see bottom line). That's how the styled theme props will be passed to LoginMenu component.