Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

reactjs - How to add a className to single .map item?

I want to add className to a .map item, but only for the one which is clicked.

Tried useState ( {state ? "class" : ""} ) but it added class for all items inside my loop. I also tried useRef but I learned that useRef does not cause re-render so result didn't update on screen.

example code:

    {posts.map((post)=> {
      return (
        <div className=`PLACE FOR CLASS` key={post.id}>
        {post.title}
        <button onClick={()=> onclick event to add class}>add</button>
        </div>
      )
    })}

So what is the way to add class only for item which is clicked in this case? ( I think I need to use Key but don't know how )

question from:https://stackoverflow.com/questions/65934907/how-to-add-a-classname-to-single-map-item

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you don't want to add this information to the main state (posts) you can create a separate list of selected ids, it'll be something like this (assuming you're using function components)

const [selectedPosts, setSelectedPosts]=useState([]);
...
{posts.map((post)=> {
  return (
    <div className={selectedPosts.includes(post.id) && "myClass"} key={post.id}>
    {post.title}
    <button onClick={()=> {setSelectedPosts(s => [...s, post.id])}}>add</button>
    </div>
  )
})}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...