Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
user1283776 Avatar asked Oct 24 '18 10:10

user1283776


2 Answers

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; `; 
like image 139
Deve Avatar answered Sep 28 '22 03:09

Deve


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}/> 
like image 25
mckvak Avatar answered Sep 28 '22 04:09

mckvak