ThirdGhostHand
ThirdGhostHand

Reputation: 397

React: Passing attribute from functional component to class component via onClick

Both of these first two snippets appear in a class component. Here's the onClick handler:

selectChoice = (id) => {
  console.log(id)
}

Here's where I call the functional component that generates both the id I need, and the onClick method.

<ReturnChoices choices={this.state.choices} selectChoice={() => this.selectChoice(id)}/>

Here's the functional component.

const ReturnChoices = ({choices, selectChoice}) => {
  return choices.map(( choice , index) => (
    <li key={index} id={index} onClick={() => { selectChoice(this.id) }}>
      {choice}
    </li>
  ))
} 

For some reason, id is coming though as 'undefined'

Upvotes: 0

Views: 1120

Answers (2)

Aprillion
Aprillion

Reputation: 22324

pass the function itself, no need to wrap in additional function:

<ReturnChoices choices={this.state.choices} selectChoice={this.selectChoice}/>

Upvotes: 1

Vivek
Vivek

Reputation: 1513

Pass id given as argument from ReturnChoices to its caller function

<ReturnChoices choices={this.state.choices} selectChoice={(id) => this.selectChoice(id)}/>

Upvotes: 1

Related Questions