user1283776
user1283776

Reputation: 21764

How to extend styled components?

I have a styled component:

interface FlexContainerProps {
    children: any;
    className?: string;
}
    
function FlexContainer(props: FlexContainerProps) {
    const Container = styled.div`
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
    `;
    return (
        <Container className={props.className}>
            {props.children}
        </Container>
    );
}

I want to be able to extend it when I use it in components.

The following does not work because the "extended" class has lower specificity (or is later in the code):

const FlexContainerExtended = styled(FlexContainer)`
    flex-direction: column-reverse;
`;

The following works but is hacky:

const FlexContainerExtended = styled(FlexContainer)`
    flex-direction: column-reverse !important;
`;

Is there another way to extend styled components?

Upvotes: 39

Views: 46994

Answers (2)

Deve
Deve

Reputation: 1779

You can just do like this:

const FlexContainer = styled.div`
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
`;


const FlexContainerExtended = styled(FlexContainer)`
    flex-direction: column-reverse;
`;

Upvotes: 83

mckvak
mckvak

Reputation: 411

type FlexContainerProps = {
    className?: string,
}

const StyledFlexContainer = styled.div<FlexContainerProps>`
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
`

export const FlexContainer: React.FC<FlexContainerProps> = props => {
    return (
        <StyledFlexContainer className={props.className} 
            {props.children}
        </StyledFlexContainer>
    );
}    

In other component u can extend your FlexContainer like this:

const FlexContainerExtended = styled.div`
        flex-direction: column-reverse;
    `;


<FlexContainerExtended as={FlexContainer}/>

Upvotes: 3

Related Questions