quinndarling21
quinndarling21

Reputation: 23

When creating buttons for each item in an array in React, how do I pass in unique onClick parameters based on the array value?

I am creating a button for each string an an array (ie. majorDivisions = ["upper", "lower"]). I need each button to have an onClick function with parameters equal to the unique value (ie. "upper" or "lower") depending on which value was used to create the button. It is creating the correct buttons but for when calling the function, the parameter is not the string but instead some class object.

return(
  <div>
    {this.state.majorDivisions.map((division) => {
      return <button onClick = {this.renderDivisionRequirements.bind(null, {division})}>{division}</button>
    })}
  </div>)

My code is successfully creating 2 buttons [lower] and [upper], however the onClick parameter {division} is appearing as a class object.

Upvotes: 2

Views: 1394

Answers (1)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

When you wrap your argument in curly braces like {division} , you are passing in an object. ie: { upper: "upper" } and { lower: "lower" }

This is recognized as a short-hand method to create an object inside a function declaration.

Just remove the curly-braces and the individual division parameter will be passed as expected to each button.

return(
  <div>
    {this.state.majorDivisions.map((division) => {
      return <button onClick = {this.renderDivisionRequirements.bind(null, division)}>{division}</button>
    })}
  </div>)

Also, to make things a bit cleaner, I would recommend turning renderDivisionRequirements() into an arrow-function so you don't have to bind this. Or using anonymous function to call it on button-click.

renderDivisionRequirements = () => {
...renderDivisionRequirements logic
}

So your return logic can just be

return(
  <div>
    {this.state.majorDivisions.map((division) => {
      return <button onClick = {() => this.renderDivisionRequirements(division)}>{division}</button>
    })}
  </div>)

Upvotes: 1

Related Questions