Passing down variable to handler in sub component in ReactJS

I have a AllPersons component, where I want to pass down a callback from my main app.js component, I want it so, I can edit a person, that I'm displaying inside my table.

My issue is that I need the id of the person, in order to change just that one person.

I'm mapping through an array of person objects and adding a button to make the callback

However, I need to pass the id inside to the handler so I can edit just that person

 <div className="col-md-6">
        <h3>All Persons</h3>
        <AllPersons persons={this.state.persons} onEdit= 
 {this.onEditHandler} id={this.id} />
      </div>


   //AllPersons.js
   {persons.map((person, i) => (

      <tr key={i}>
        <th>{person.age}</th>
        <th>{person.name}</th>
        <th>{person.gender}</th>
        <th>{person.email}</th>
        <a href="/#" onClick= {props.onEdit} id={person.id}>edit</a>
      </tr>


    //handle method inside App.js
      onEditHandler = (event) =>{
   event.preventDefault();
    console.log("editet")

  }

I was considering setting the id as a state, but I think that would be too much,

Upvotes: 0

Views: 33

Answers (1)

Rafael Hovsepyan
Rafael Hovsepyan

Reputation: 781

Use curryng for this case

Define you hander like this

editHandler = id => event => {
   // you have id here
}

And use it in JSX

<a href="/#" onClick= {props.onEdit(person.id)}>edit</a>

Upvotes: 2

Related Questions