简体   繁体   中英

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?

For one style:

const Wrapper = styled.div`
    background: red;
    color: ${props => props.myProps === 'ok' && 'white'};
`;

For multiple styles:

const Wrapper = styled.div`
    background: red;
    ${props => {
        if (props.myProps === 'ok') return `
            background-color: black;
            color: white;
        `
    }}
`;

Another option is to use styled.css :

// Define a pure group of css properties
const okStyle = styled.css`
    background-color: black;
    color: white;
`;

// Reuse okStyle inside a styled component
const Wrapper = styled.div`
    background: red;
    ${props => props.myProps === 'ok' && okStyle}
`;

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

const Wrapper = styled.div(
  (props) => css`
    background: red;

    ${props.isOK &&
    css`
      background-color: black;
      color: white;
    `}
  `
);

You should add

const Wrapper = styled.div`
  background: red;
  color: ${p => p.isOk ? 'white' : 'green'}; // color will be added only if this.props.myProps == 'ok', else color will be green
`;

To send this props you should use syntax like

return (
  <Wrapper isOk={true}>Some text</Wrapper>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM