Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 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 Reply

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>
  )
})}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...