Home > Mobile >  What is the best way to handle enum prop in styled-components
What is the best way to handle enum prop in styled-components

Time:03-29

I am using styled-components in combination with typescript

Let say I have a typescript enum

 enum MessageLevel {
   info,
   warning,
   danger
 }

And I have a styled text component, which should change text color (green, yellow, red) depending on prop passed to it.

According to styled-components documentation I could do something like this.

But this code looks quite cluttered. May be there is another solution?

const Message = styled.div<{ level: MessageLevel }>`
  ${(props) =>
    props.level === MessageLevel.low &&
    css`color: green;`
  }
  ${(props) =>
    props.level === MessageLevel.warning &&
    css`color: yellow;`
  }
  ${(props) =>
    props.level === MessageLevel.danger &&
    css`color: yellow;`
  }
`;

CodePudding user response:

You could combine the props.level checks into one line to clean up the code as-is. In my example I'm using a ternary which needs one of the options to be a default/fallback. I used "gray" in my example, but you could use green/yellow/red if you prefer:

const Message = styled.div<{ level: MessageLevel }>`
  color: ${(props) =>
    props.level === MessageLevel.low
      ? "green"
      : props.level === MessageLevel.warning
      ? "yellow"
      : props.level === MessageLevel.danger
      ? "red"
      : "gray"}
`;

You could also make a map that maps your enum value to a color value and use that instead of the conditionals. This is cleaner in my opinion:

const messageLevelColorMap = {
  [MessageLevel.low]: "green",
  [MessageLevel.warning]: "yellow",
  [MessageLevel.danger]: "red",
}

const Message = styled.div<{ level: MessageLevel }>`
  color: ${(props) => messageLevelColorMap[props.level]}
`;
  • Related