DEV Community

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

Posted on

4 4

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.

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay