How to avoid long conditional rendering with styled components?

Viewed 30

I'm working on a project using a lot of different variables. Depending on props, they will render a certain color (for example). The problem is that with the amount of variables my code ends up really long. Is there a solution to clean up this code?

This is an example:

Variables:

const Variables = {
    Colors: {
        Primary50: "rgb(244, 246, 247)",
        Primary100: "rgb(209, 218, 225)",
        ...rest of colors
    },

    ...rest of variables
}

And the styled component:

const Component = styled.div<{ $color: number }>`
    background-color: ${({ $color }) =>
        $color === 50
            ? Variables.Colors.Primary50
            : $color === 100
            ? Variables.Colors.Primary100
            : ...rest};
`

I tried something like this, but it is not working:

const Component = styled.div<{ $number: number }>`
    background-color: ${Variables.Colors.Primary[$number]};
`

Thanks for your answers!

1 Answers

Better use switch instead of ternary operator for your instance. The second aproach Primary[$number] is wrong, it look like Variables.Colors.Primary.100 you need to enclose Primary50 entirely in square brackets.

const Variables = {
  Colors: {
    Primary50: 'rgb(244, 246, 247)',
    Primary100: 'rgb(209, 218, 225)',
  },
};

const Component = styled.div<{ $color: number }>`
  background-color: ${props => {
    switch (props.$color) {
      case 50:
        return Variables.Colors.Primary50;
      case 100:
        return Variables.Colors.Primary100;
      default:
        return 'white';
    }
  }};
`;

const Component2 = styled.div<{ $number: 50 | 100 }>`
  background-color: ${props => Variables.Colors[`Primary${props.$number}`]};
`;

function App() {
  return (
    <div className="App">
      <Component $color={100}>First example</Component>
      <Component2 $number={50}>Second example</Component2>
    </div>
  );
}

export default App;

Edit dazziling-code

Related