Given two dynamic properties:
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
You can write a function that will return the styling given the properties as arguments. here you go: solution
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}
`
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.