Search code examples
reactjsstyled-components

Props conditional rendering using styled-components


I am using styled-components library inside a React application and I have this block for example:

const Wrapper = styled.div`
  background: red;
`;

I need to add some other style if a prop has a set value, something like:

const Wrapper = styled.div`
  background: red;
  color: white; // color should be added only if this.props.myProps == 'ok'
`;

What's the best way to do this?


Solution

  • Another syntax option.
    This is actually how I write all my styled-components now. It makes things easier to iterate/update.

    import styled, { css } from "styled-components";
    
    const Wrapper = styled.div(
      (props) => css`
        background: red;
    
        ${props.isOK &&
        css`
          background-color: black;
          color: white;
        `}
      `
    );