How can I get a styled component to render different css rules depending on the state of the React component in which it is rendered?
The below does not work:
class Container extends React.Component<ContainerProps, ContainerState> {
constructor(props: ContainerProps) {
super(props);
this.state = {
highlight: true,
dark: false
};
}
OuterWrapper = styled.div`
display: inline-block;
padding: 20px;
${this.state.dark && `
background-color: 'gray';
`};
`;
return (
<this.OuterWrapper>
...
</this.OuterWrapper>
);
}
TypeError: Cannot read property 'dark' of undefined at new Container
The best way to achieve that is through passing a prop to the element that you get from styled-comopnent.
// outside of the component
interface OuterWrapperProps {
dark: boolean;
}
const OuterWrapper = styled.div<OuterWrapperProps>`
display: inline-block;
padding: 20px;
${props => props.dark && css`
background-color: 'gray';
`};
`;
And when you render that element:
...
<OuterWrapper dark={this.state.dark}> ... </OuterWrapper>
...
And you still have control over the theme from your state!
Doing so, helps the readability of your code, as well as following what the docs suggest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With