Ad

ReactJS Cannot Read Property 'bind' Of Undefined

- 1 answer

I am trying to learn reactjs by making some simple apps. I thought I had figured the basics out, until I stumbled upon a situation where I use .bind. I am trying to make a small list that, when clicked, will remove the clicked list-item. The logic behind it is not implemented yet as I keep running into the same error. I have looked through other questions, but for some reason I haven't managed to make it work, so if this is reposted I am sorry.

"Cannot read property 'bind' of undefined"

The code in question is implemented below. I would really appreciate some help on this. I know it's a really basic problem, but hey. Can't always be perfect.

var React = require("react");
var ReactDOM = require("react-dom");

var dataList = ["Apples","Bananas", "Oranges", "Pinapple"];

var Wrapper = React.createClass({
	handleClick: function(item, event) {
		console.log("clicked");
	},
	render: function() {
		var allData = this.props.datalist;
		return(
			<div>
				<ul>
					{allData.map(function(listpoint,i) {
						return(
							<li onClick={this.handleClick.bind(this,listpoint)} key={"list" + i}>{listpoint} [{i}]</li>
						);
					})}
				</ul>
			</div>
		);
	}
});

ReactDOM.render(
	<Wrapper datalist={dataList}/>,
	document.getElementById("container")
);

Ad

Answer

You should set this for .map, because this in .map callback does not refer to Wrapper, it refers to global scope(in browser it is window) or if you use strict mode it will be undefined

allData.map(function(listpoint,i) {
  return <li 
    onClick={this.handleClick.bind(this,listpoint)} 
    key={"list" + i}>{listpoint} [{i}]</li>;
}, this);
__^^^^^^

Example

Ad
source: stackoverflow.com
Ad