3

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

0

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. It works now.
This also works for _.map(items, iteratee function, this)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.