简体   繁体   中英

How to pass props to .mapped elements with styled-components?

I've been hitting my head against a wall with this one and I can't quite grasp what's the issue here. I am pulling some data from API. It's a simple object that contains username, score and isOwner which is basically information if the username equals currently logged user. Now, if isOwner is true i want to style that li position differently. So lets say that's how my map looks like:

const List = myData.map((el, i) => (
    <li key={el.name} isowner={el.isOwner ? 1 : 0}>
      {i + 1}. {el.name}
      <span>{el.score}</span>
    </li>
  ));

So every li element is generated in a styled ul component. Now, looking at the styled component list, it looks like:

export const ScoreList = styled.ul`
  width: 80%;
  display: flex;
  flex-direction: column;

  li {
    border: ${props =>
      props.isowner === 1 ? '2px solid yellow' : '1px solid black'};
    border-radius: 5px;
  }`

for some reason it ignores the value of isowner and displays everything with the black border.

Now looking at chrome dev tools I've noticed something odd.

<li isowner="1">...</li>
<li isowner="0">...</li>
<li isowner="0">...</li>

I can see the 'prop' being put there like this, which I can't notice in any other case when I'm passing props. It looks like the logic is working well but it just doesn't see the element as a prop.

Also, I am using isowner instead of isOwner because otherwise I'm getting a following warning:

React does not recognize the `isOwner` prop on a DOM element. 
If you intentionally want it to appear in the DOM as a custom attribute, 
spell it as lowercase `isowner` instead. 
If you accidentally passed it from a parent component, remove it from the DOM element.

I've tried different methods, instead of isOwner I was comparing el.name with username that I could yoink from redux, results were the same, I got the '1' or 'true' right where I needed it but I just couldnt pass it further.

I would be very very thankful if any of you has an idea about how to deal with this.

this might help you:

export const ScoreLi = styled.li`

border: ${props =>
  props.isowner === 1 ? '2px solid yellow' : '1px solid black'};
border-radius: 5px;`



const List = myData.map((el, i) => (
<ScoreLi key={el.name} isowner={el.isOwner ? 1 : 0}>
  {i + 1}. {el.name}
  <span>{el.score}</span>
</ScoreLi>
));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM