0

I'm learning to use React and I have a problem about how to pass the id using a button.

I have recover data for my fetch from: https://jsonplaceholder.typicode.com/users

My js page:

handleClick(){
    alert("ALERT " + this.props);
}


render(){
    const listMeetings = this.props.meetings.map((meeting) => 
    <li key={meeting.id}>{meeting.name}
    <button key={meeting.id} onClick={() => this.handleClick(meeting.id)} value={meeting.id}>{'Details'}</button>
    </li>);
    return(
        <div>
                   <ul>{listMeetings}</ul>
        </div>
    )
}
}

So at the moment I have a list of name and a button, immediately next to each name. What I would to do is to pass the id of every name, when the button is clicked (at the moment I would print only an alert with the id.

With my code, I have understand that I pass all the array (so I have 10 object).

How can I do? thank you.

2 Answers 2

1

You have an error in your handleClick you pass the meeting.id as a param but it's missing in the functions declaration

handleClick(id){
  alert("ALERT " + id);
}


render(){
  const listMeetings = this.props.meetings.map((meeting) =>
    <li key={meeting.id}>{meeting.name}
      <button key={meeting.id} onClick={() => this.handleClick(meeting.id)} value={meeting.id}>{'Details'}</button>
    </li>);
  return(
    <div>
      <ul>{listMeetings}</ul>
    </div>
  )
}
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Jack23 it happens to all, don't worry
1

Try anonymous function version instead:

handleClick = (id){
    alert("ALERT " + id);
}

render(){
    const listMeetings = this.props.meetings.map((meeting) => 
    <li key={meeting.id}>{meeting.name}
    <button key={meeting.id} onClick={(id) => this.handleClick(meeting.id)} value={meeting.id}>{'Details'}</button>
    </li>);
    return(
        <div>
                   <ul>{listMeetings}</ul>
        </div>
    )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.