Search code examples
reactjstypescriptstyled-components

How to EXTEND imported component styled components


I cannot extend my imported component. I was looking into styled components docs and find that in v4+ should works prop "as", but it doesnt.

COMPONENT:

    type Props = {
        padding: string,
        justify: string
    }

    const FlexContainer = styled.div<Props>`
        padding: ${props => props.padding};
        display: flex;
        flex-wrap: wrap;
        justify-content: ${props => props.justify};
    `

    export const Flexcontainer: React.FC<Props> = props =>{
        return (
        <FlexContainer padding={props.padding} justify={props.justify}>
            {props.children}
        </FlexContainer>


 )
}

EXTENDED STYLE:

import { Flexcontainer }  from '../../reusable/FlexContainer';

const FlexContainerExtended = styled.div`
  color: red;
`

USE:

<FlexContainerExtended
  padding={null}
  justify={"flex-start"}
  as={Flexcontainer}>

Solution

  • You can just pass the base component to the styled function to override it.

       type Props = {
            padding: string,
            justify: string
        }
    
        const FlexContainer = styled.div<Props>`
            padding: ${props => props.padding};
            display: flex;
            flex-wrap: wrap;
            justify-content: ${props => props.justify};
        `
        const FlexContainerExtended = styled(FlexContainer)`
           color: red;
        `
    
        export const Flexcontainer: React.FC<Props> = props =>{
            return (
            <FlexContainer padding={props.padding} justify={props.justify}>
                {props.children}
            </FlexContainer>
     )
    }
    // And use it like this
    <FlexContainerExtended
      padding={null}
      justify={"flex-start"}/>