2
votes

Given two dynamic properties:

  1. currentColor
  2. cardsRemaining

And const colors = ['blue', 'red', 'green', 'yellow', 'orange']

With Styled components, how can I dynamically set the box-shadow property? Where the number cardsRemaining assigns the number of box-shadow values.

For example, cardsRemaining == 2:

box-shadow:
    8px 0 0 0 colors[current+1],
    16px 0 0 0 colors[current+2];

For example, cardsRemaining == 4:

box-shadow:
    8px 0 0 0 colors[current+1],
    16px 0 0 0 colors[current+2],
    24px 0 0 0 colors[current+3],
    32px 0 0 0 colors[current+4];

And where currentColor is used to assign the color in each box-shadow value.

So if cardsRemaining == 4 && currentColor == blue:

box-shadow:
    8px 0 0 0 red,
    16px 0 0 0 green,
    24px 0 0 0 yellow,
    32px 0 0 0 orange;

Or, if cardsRemaining == 2 && currentColor == yellow:

box-shadow:
    8px 0 0 0 orange,
    16px 0 0 0 blue;

How would you approach a problem like this with styled-components?

Thank you

2

2 Answers

5
votes

You can write a function that will return the styling given the properties as arguments. here you go: solution

2
votes

Inside styled components, it is possible to access the props. Therefore, you can do something like below -

export getBoxShadow = ({cardsRemaining, currentColor }) => logicHere

export const StyledComponent = styled.div`box-shadow: ${getBoxShadow};`

Edit from @OwlyMoly: If you just want to pass the color:

    const StyledComponent = styled.div`
     box-shadow: 8px 0 0 0 ${props => props.colorToBe}
    `