Coding is Life
Coding is Life

Reputation: 53

How to onClick in map?

I map elements, and put onClick button, that takes choosen element, and make needed actions with it. problem is how to make onClick={function} to know which element is selected? Because its always take last map element (English grammar is not my strong side).

<div className={styles.list}>
      {users.map(u => (
          <div onClick={handleClick}}> // this is function that picks element
          <UserItem
              key={u.id}
              user={u}
          /> </div>
      ))}
  </div>

Upvotes: -1

Views: 4859

Answers (3)

Ioannis Potouridis
Ioannis Potouridis

Reputation: 1316

Your handler should look like this.

const handleClick = (user) => () => {
  // do whatever you want with the clicked user here.
}

And you should pass your user like so.

<div className={styles.list}>
  {users.map(u => (
    <div onClick={handleClick(u)}}> // this is function that picks element
      <UserItem
        key={u.id}
        user={u}
      /> 
    </div>
  ))}
</div>

That's your solution but please don't rest there, search more for Closures because you'll work with them a lot in your React projects.

Upvotes: 0

user13077374
user13077374

Reputation:

I think you should pass the u.id to the handleClick function.

<div className={styles.list}>
    {users.map(u => (
       <div onClick={() => handleClick(u.id)}>
           ...
       </div>
    ))}
</di>

Upvotes: 1

Philipp Meissner
Philipp Meissner

Reputation: 5482

Just pass the u variable that represents a single user like so:

<div className={styles.list}>
  {users.map(u => (
  <div onClick={() => this.handleClick(u)}> // this is function that picks element
  <UserItem
      key={u.id}
      user={u}
  /> </div>
))}

Read up in their official docs.

Upvotes: 0

Related Questions