When extending a base component using styled components, is there a way to access props from the base component in the extended component?
Here's the base component and its styled component. On line 8 I pass in isOpen
. In the styled component I toggle between two colors for the background colors, which are based on isOpen
.
const StyledBaseComponent = styled.button`
background-color: ${({ isOpen }) => (isOpen ? 'cyan' : 'orange')};
`
function BaseComponent(props) {
const [isOpen, toggleOpen] = useState(false)
return (
<StyledBaseComponent {...props} isOpen={isOpen} onClick={() => toggleOpen(!isOpen)}>
isOpen - {String(isOpen)}
</StyledBaseComponent>
)
}
Here's the extended component and its styled component. On line 2 I try to use isOpen
from the parent to toggle colors but it's undefined so the color will always be yellow
.
const StyledExtendedComponent = styled(BaseComponent)`
background-color: ${({ isOpen }) => (isOpen ? 'pink' : 'yellow')};
`
function ExtendedComponent() {
return <StyledExtendedComponent />
}
Here's a codesandbox for the issue: https://codesandbox.io/s/4q60qqx027. The left button, which is the base component, works as expected. The right button, which extends the base component, doesn't change colors.