DEV Community

Cover image for Exporting Styled Component variants in reusable components
Adrien Rahier
Adrien Rahier

Posted on

Exporting Styled Component variants in reusable components

In the first part of this serie we have seen how to create Styled Component variants within the same file.

Now, let's say you want to create a multi-variant component that is reused all-across you app. How would you do this in a scalable way?

Solution

Over time, I have tried several techniques to do this (more about this at the end of this article) but one really shined.
Creating an extra Wrapper around the Default Component!

import styled from 'styled-components';

// Note that having a default class is important
const StyledCTA = ({ className = 'default', children }) => {
    return <Wrapper className={className}>{children}</Wrapper>;
};

/*
 * Default Button styles
 */
const Wrapper = styled.button`
    color: #000;
`;

/*
 * Custom Button Variant 1
 */
export const StyledCTAFushia = styled(StyledCTA)`
    && {
        color: fuchsia;
    }
`;

/*
 * Custom Button Variant 2
 */
export const StyledCTADisabled = styled(StyledCTA)`
    && {
        color: ${(props) => props.theme.colors.grey.light};
    }
`;

export default StyledCTA;

Enter fullscreen mode Exit fullscreen mode

Usage

import StyledCTA, { StyledCTADisabled, StyledCTAFushia } from 'components/StyledCTA';

const Page = () => {
    return (
        <>
            <StyledCTA>Default CTA</StyledCTA>
            <StyledCTADisabled>Disable CTA</StyledCTADisabled>
            <StyledCTAFushia>Fuchsia CTA</StyledCTAFushia>
        </>
    )
};
Enter fullscreen mode Exit fullscreen mode

Additional techniques

For some more advance usage I would also recommend using composable CSS variables.

Another alternative is also to use a dedicated library on top of Styled Components.

Top comments (0)