How to extend styled components?

user1283776 picture user1283776 · Oct 24, 2018 · Viewed 11.4k times · Source

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?

Answer

Deve picture Deve · Oct 24, 2018

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;
`;