Ilja
Ilja

Reputation: 46529

Unable to execute onClick function in mapped ellement

I am trying to add an on click function to my list tags that are mapped from an array, i.e:

{this.props.addresses.map((address, index) =>
   <li key={`address-${index}`} onClick={this.addressClick}>{address.prediction}</li>
)}

addressClick is defined in constructor like this:

  constructor (props) {
    super(props)
    this.addressClick = this.addressClick.bind(this)
  }

and as a function in the class like this

  addressClick () {
    console.log('Clicked')
  }

When I click on my list tag nothing happens, I don't see any console statements.

Upvotes: 1

Views: 34

Answers (3)

alwayslearning
alwayslearning

Reputation: 137

Your code should work unless I am missing something. This works for example:

const arr = [1,2,3,4]

class App extends Component {
  constructor(props) {
    super(props)
    this.addressClick = this.addressClick.bind(this)
  }

  addressClick () {
    console.log('Clicked')
  }

  render() {
    return (
      <ul>
        {arr.map((address, index) =>
          <li key={`address-${index}`} onClick={this.addressClick}>{address}</li>
        ) }
      </ul>
    )
  }
}

Upvotes: 0

vijayst
vijayst

Reputation: 21856

Bind this to the map method:

{this.props.addresses.map((address, index) =>
   <li key={`address-${index}`} onClick={this.addressClick}>{address.prediction}</li>
).bind(this)}

Upvotes: 2

David Antoon
David Antoon

Reputation: 825

Suggestion

You can implement this by passing the index to another function and then call addressClick().

function clickListener ( index ) {
    var clickedAddress = addresses[index];
    addressClick(clickedAddress.prediction);
}

Result:

{this.props.addresses.map((address, index) =>
    <li key={`address-${index}`} onClick={`clickListener(${index})`}</li>
)}

Upvotes: 0

Related Questions