1
votes

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

1

1 Answers

8
votes

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 the control over the theme from your state!

Doing so, helps the readability of you code, as well as following what the docs suggest.