Skip to content Skip to sidebar Skip to footer

How To Style Individual Elements Created With Array.map Using Styled-components?

The goal is to be able to target each unique element in order to give it unique styling. In my code the array in question is an array of objects, and each dummyElement will have an

Solution 1:

According to the official documentation. https://styled-components.com/ I think the solution comes in this way. Try it, and tell me if it works.

/ dummyElement.styled.js file

exportconst dummyElement = styled.a`
  font-size: 20px;
  ${ props => props.longValue === 'someLongitudeValue' && css`background-color: white;
  `}${ props => props.longValue === 'otherLongitudeValue' && css`background-color: green;
  `}
`; // Styles all the dummyElements, how to style them individually?// dummyElement.JSX file import { dummyElement } from"./dummyElement.styled";

<>
  props.dummyArray.map((current, index) => (
    <dummyElementkey={index}href={"https://dummywebsite/" + current.value}
      longValue={current.long}
    >
      {current.value}
    </dummyElement>
  ))
</>

Solution 2:

You could pass in values for dynamic styling through the id property and then parse them in the dummyElement styled component like this:

// Define your dynamic styled components something like thisexportconstDummyElement = styled.div`
  font-size: 20px;
  padding: ${props => Number(props.id.split('-')[2])}px;
  background-color: ${props => props.id.split('-')[1]};
  color: #FBE7FD;
`;

// Then when using the DummyComponent do something like this<DummyElementid='dummy1-coral-100' /><DummyElementid='dummy2-indianred-50' /><DummyElementid='dummy3-pink-20' />

Post a Comment for "How To Style Individual Elements Created With Array.map Using Styled-components?"