Matt Saunders Matt Saunders - 17 days ago 8
React JSX Question

Accessing a method inside a ReactJS component

I'm still learning ReactJS. I'm challenging myself to write a very basic todo app (as one does) and I'm having an issue calling an onClick function.

var List = React.createClass({

handleClick: function () {
alert("Clicked!");
},

render: function () {

var list = this.props.items;
var items = list.map(function(item){
return (
<li style={{borderBottom:'1px solid red'}}>
<label onClick={this.handleClick}>
<input type="checkbox" />
{item}
</label>
</li>
);
});

return (
<ul>{items}</ul>
)
}
});


The issue here is that onClick={this.handleClick} cannot be called because it is not inside the return call in the render function. What do I need to do to access handleClick from inside the map function?

Answer

The second argument for the map function is a value to define the scope of this when executing the callback.:

.map( callback( currentValue, index, array), value_for_this/scope_to_run_in )

So you can modify your map function as follows:

var items = list.map(function(item){
  return (
    <li style={{borderBottom:'1px solid red'}}>
      <label onClick={this.handleClick}>
        <input type="checkbox" />
        {item}
      </label>
    </li>
  );
}, this);

You could also use an arrow function which where this is implicitly bound:

var items = list.map((item) => {
  return (
    <li style={{borderBottom:'1px solid red'}}>
      <label onClick={this.handleClick}>
        <input type="checkbox" />
        {item}
      </label>
    </li>
  );
});
Comments