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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x