Search code examples
javascriptreactjsstyled-components

reactjs + styled-components with stateful component - my styles can't see props


Why can't props be seen when using a class/stateful component:

const StyledTitle = styled.h1 `
  color: ${props => (props.primary ? "royalblue" : "black")};
`;

class Title extends Component {
  render() {
    return <StyledTitle > {
      this.props.children
    } < /StyledTitle>;
  }
}

const App = () => ( 
  <div>
    <Title>Hi, Alice!</Title>
    <Title primary>Hi Bob, you are awesome!</Title>
  </div>
);

Here is Styled-Components' example: Adapting based on props

Demo: https://codesandbox.io/s/oxqz3o30w5


Solution

  • You are not passing the primary property to the styled component so it can render the logic depending on the primary property. Just add it in the component declaration.

    const StyledTitle = styled.h1 `
        color: ${props => (props.primary ? "royalblue" : "black")};
    `;
    
    class Title extends Component {
      render() {
        return <StyledTitle primary={this.props.primary}> {
          this.props.children
        } < /StyledTitle>;
      }
    }
    
    const App = () => ( 
      <div>
        <Title>Hi, Alice!</Title>
        <Title primary>Hi Bob, you are awesome!</Title>
      </div>
    );