I´m new to React and I´m trying to connect an onClick event to an image to see what object that has been pressed but does not get it to work, I´ve tried several answers that I found on this site but none work, might be because of "var createItem"?
/** @jsx React.DOM */
var React = require("react");
var Firebase = require("firebase");
// CHILD
var CardsList = React.createClass({
render: function() {
var createItem = function(card, index) {
return <div id='card' key={ index }><img onClick={ this.props.onClick.bind(null, this) } src= { card.url }/></div>;
};
return <div id='cards'>{ this.props.cards.map(createItem) }</div>;
}
});
//PARENT
var DeckCalculator = React.createClass({
getInitialState: function() {
this.cards = [];
this.userCards = [];
return {cards: [], name:"default", url:"defaultURL"};
},
handleOnAdd: function(ponent, event){
// Add the clicked card to userCards[]
},
render: function() {
return (
<div>
<h3>All Cards</h3>
<CardsList onClick={ this.handleOnAdd } cards={ this.state.cards } />
</div>
);
}
});
This code gives the error: Uncaught TypeError: Cannot read property 'onClick' of undefined
I´m new to React and I´m trying to connect an onClick event to an image to see what object that has been pressed but does not get it to work, I´ve tried several answers that I found on this site but none work, might be because of "var createItem"?
/** @jsx React.DOM */
var React = require("react");
var Firebase = require("firebase");
// CHILD
var CardsList = React.createClass({
render: function() {
var createItem = function(card, index) {
return <div id='card' key={ index }><img onClick={ this.props.onClick.bind(null, this) } src= { card.url }/></div>;
};
return <div id='cards'>{ this.props.cards.map(createItem) }</div>;
}
});
//PARENT
var DeckCalculator = React.createClass({
getInitialState: function() {
this.cards = [];
this.userCards = [];
return {cards: [], name:"default", url:"defaultURL"};
},
handleOnAdd: function(ponent, event){
// Add the clicked card to userCards[]
},
render: function() {
return (
<div>
<h3>All Cards</h3>
<CardsList onClick={ this.handleOnAdd } cards={ this.state.cards } />
</div>
);
}
});
This code gives the error: Uncaught TypeError: Cannot read property 'onClick' of undefined
Share Improve this question edited Apr 2, 2015 at 14:13 Deduplicator 45.8k7 gold badges72 silver badges123 bronze badges asked Nov 21, 2014 at 13:42 Jonas Linne KalmarJonas Linne Kalmar 952 silver badges11 bronze badges1 Answer
Reset to default 3Your createItem
has the wrong context.
var createItem = function(card, index) {
return (
<div id='card' key={index}>
<img onClick={this.props.onClick.bind(null, this)} src={ card.url } />
</div
);
}.bind(this);
Notice the .bind(this)
at the end.
For more information on why this
is (haha), check out this article https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Operators/this