ReactJS Cannot read property 'bind' of undefined

All we need is an easy explanation of the problem, so here it is.

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")
);

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply