Home > database >  How to forward style object to styled component?
How to forward style object to styled component?

Time:01-07

Imagine I create a react component

and users can use it but I want to allow users to pass a typical style object to it:

<Text style={{color:"red",borderRadius:10}}/>

Now imagine this Text component uses styled component inside:

// Inside Text Component render method
...
return (
    <TextContainerStyled {...props.style}> 

TextContainerStyled is a styled component. How do I forward the style object which user supplies to Text component to TextContainerStyled ?

CodePudding user response:

Based on what you wrote, I think you need an implementation like this

const TextContainerStyled = styled.div``

const Text = (props)=>{
  return (
    <TextContainerStyled style={props.style}>
     {/* Other children here */}
    </TextContainerStyled/>
  )
}

This doesn't however forward refs, if you want to forward a the Text ref to the TextContainer too. You might need to read about it here

  •  Tags:  
  • Related