Search code examples
reactjsstyled-components

Is it possible to define a list of re-usable styled components that can be used without having to redefine said styled component each time?


Basicaly what I'm trying to do is create one single component that has a list of re-usable styled components that I can use instantly without having to redefine / extend said styled component.

For the component that has a list of re-usable styles I currently export an object that has all the re-usable styles like so:

import styled from 'styled-components';
const ReusableStyles = {
    BgGreen : styled.div`
        background-color: #50ccb7;
        color: #FFF;
    `,
    TextLeft : styled.div`
        text-align: left;
        width: 50%;
    `
}
export default ReusableStyles;

I'm currently using these re-usable styles like so

import React from 'react'
import styled from 'styled-components'
import ReusableStyles from './reusableStyles.js'

const TestWithBgGreen = styled(ReusableStyles.BgGreen)`
`;

class Test extends React.Component {
    render() {
        return (
            <TestWithBgGreen>
                Test Text with green background
            </TestWithBgGreen>
        );
    }
}

export default Test;

Now my problem with this is that I have to re-define / extend ReusableStyles.BgGreen each time I use this, even though I'm not adding any style properties.

I'd prefer to use the styled component directly like so:

<ReusableStyles.BgGreen>
    Test Text with green background
</ReusableStyles.BgGreen>

This obviously does not work.

Is there any way to create a single component that has a collection of re-usable styles that can be used without having to redefine / extend that styled component each time?


Solution

  • This is not working due to the way you're exporting and importing your components. Right now you're adding them to an object and then exporting that object. So you're forced to get to the styled-components through that ReusableStyles object.

    This is what you want to do:

    const BgGreen = styled.div`
              background-color: #50ccb7;
              color: #FFF;
          `,
    const TextLeft = styled.div`
           text-align: left;
           width: 50%;
          `
    
    export { 
      BgGreen,
     TextLeft,
    
    }
    

    Then import them as:

    import {BgGreen} from './reusableStyles.js'
    

    And use them as any other component

    <BgGreen>
    My Text
    </BgGreen>
    

    Another way to export them if you want to keep your reusable object:

    export { ... ReusableStyles }
    

    And you can use default export in case you want to use the object for some reason like you're already doing.