-1

I have a component which renders the following:

render() {
  return (
    <div className = "events card" >
      <div key = {each.id}> 
        <ul>
          <li className = "card-text">Venue Name: {each.name} </li>
          <li className = "card-text">Country: {each.country} </li>
          <li className = "card-text">City: {each.city} </li>
          <li className = "card-text">Date: {each.date}</li>
        </ul>
      </div>
      <a onClick = {this.addToFavourites.bind(this)}>
        <Button text = "Add to Favourites"/>
      </a>
    </div
  );
}

addToFavourites() {
... do something
}

When I call addToFavourites, I want to pass the name, country, city and date to this function as it is going through an array of events so I don't know how else the function will do what it's supposed to do with the selected data.

wentjun
  • 40,384
  • 10
  • 95
  • 107
Shauna
  • 181
  • 10

2 Answers2

4

THis is what you can do:

<a onClick = {() => this.addToFavourites(each)}><Button text = "Add to Favourites"/></a>

This will ensure that the object will be passed to the addToFavourites method.

And from there, you can access the properties from each in the method itself.

addToFavourites(each) {
  const { name, country, city, date } = each;
  // do the rest 
}
wentjun
  • 40,384
  • 10
  • 95
  • 107
1

Answer by @wentjun is very much correct. I just want to propose an alternative solution.

You can pass the arguments you want to bind. But you should also know both these practices are not advisable. Read more here Why shouldn't JSX props use arrow functions or bind?

render() {
  return (
    <div className = "events card" >
      <div key = {each.id}> 
        <ul>
          <li className = "card-text">Venue Name: {each.name} </li>
          <li className = "card-text">Country: {each.country} </li>
          <li className = "card-text">City: {each.city} </li>
          <li className = "card-text">Date: {each.date}</li>
        </ul>
      </div>
      <a onClick = {this.addToFavourites.bind(this, each)}>
        <Button text = "Add to Favourites"/>
      </a>
    </div
  );
}

addToFavourites(each) {
  const { name, country, city, date } = each;
  // do the rest 
}
vatz88
  • 2,422
  • 2
  • 14
  • 25