Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styled component with access to React component state?

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

like image 954
user1283776 Avatar asked Jul 17 '26 07:07

user1283776


1 Answers

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.

like image 169
Hasan Sh Avatar answered Jul 18 '26 20:07

Hasan Sh