Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: trying to add an onClick to a li tag but the click handler function is undefined

Tags:

reactjs

I am new to react, so I don't know much about it. I am trying to add a click handler to a li but the function seems to be undefined?

var ActivityList = React.createClass({
  getInitialState: function() {
    return {name:"test"};
  },
  handleClick:function(e){
    console.log(e.target.name);
  },
  render:function(){
    return (
      <ul>
        {this.props.data.map(function(game){
         return <li onClick={this.handleClick} name={game.name}>{game.name}</li>;
        })
      }
      </ul>);
  }
});

I am wondering if it is because i have my scoping wrong here?

like image 343
user629283 Avatar asked Jan 31 '16 18:01

user629283


People also ask

Can we use onClick in LI tag?

The onclick attribute is part of the Event Attributes, and can be used on any HTML elements.

How do you add onClick to a React function?

Adding EventsReact events are written in camelCase syntax: onClick instead of onclick . React event handlers are written inside curly braces: onClick={shoot} instead of onClick="shoot()" .

Why this is undefined in event handler React?

This is because when you use an arrow function, the event handler is automatically bound to the component instance so you don't need to bind it in the constructor. When you use an arrow function you are binding this lexically.


2 Answers

Set this to .map, because in .map callback this refers to global scope(in browser it is window or undefined if you use strict mode)

this.props.data.map(function(game) {
  return <li onClick={this.handleClick} name={game.name}>{game.name}</li>;
}, this);
  ^^^^^

Example

like image 192
Oleksandr T. Avatar answered Sep 16 '22 15:09

Oleksandr T.


You can also use an arrow function to avoid binding this in the function at all:

this.props.data.map(game =>
    <li onClick={this.handleClick} name={game.name}>{game.name}</li>
)
like image 45
Lynn Avatar answered Sep 19 '22 15:09

Lynn