Search code examples
javascriptreactjsstyled-components

How can I make multiple styling for only one prop in React Styled Components?


I'm using Styled Components in react, and I want to wrap all the styles I want for only one prop (it's a conditional prop). Right now I have something like this:

<ContentSty
    flexDirection={abilityScores ? "column" : "row"}
    flexWrap={abilityScores ? "no-wrap" : "wrap"}
    cardDisplay={abilityScores ? "flex" : "block"}
    cardHeight={abilityScores ? "auto" : "5rem"}
    cardTextMargin={abilityScores ? "auto 0.5rem" : "0.2rem 0"}
    hoverShadow={abilityScores ? "none" : "0px 0px 14px gold"}
    hoverCursor={abilityScores ? "auto" : "pointer"}
>

I always do the same check: if the variable abilityScores === true then have this value, else have this other one. Then, in my styles, I have a lot of some-css-prop: ${(props) => props.someProp}; and it gets kind of messy

Is there a way to just wrap all the styles for abilityScores === true in one prop, then just pass a unique prop like abilityScore={abilityScore === true ? allTheseStylings : ''}, or a cleaner way, instead of just making a lot of props?


Solution

  • See the documentation on StyleObjects here: https://styled-components.com/docs/advanced#style-objects

    You can use the props of abilityScore to conditionally style your component.

    For example:

    const ContentSty = styled.div(props => ({
      flexDirection: props.abilityScores ? "column" : "row",
      flexWrap: props.abilityScores ? "no-wrap" : "wrap",
      cardDisplay: props.abilityScores ? "flex" : "block",
      cardHeight: props.abilityScores ? "auto" : "5rem",
      cardTextMargin: props.abilityScores ? "auto 0.5rem" : "0.2rem 0",
      hoverShadow: props.abilityScores ? "none" : "0px 0px 14px gold",
      hoverCursor: props.abilityScores ? "auto" : "pointer",
    });
    
    ...
    
    <ContentSty abilityScores={true} />