vesperae vesperae - 3 months ago 18
React JSX Question

ReactJs event passed from Container to Presentational Components

Trying to wrap my head around passing events from Container to Presentational components.

As I understand it I attach the event to the Presentational/view level component. But I pass the functionality from the Container component to the Presentational component as a prop. I'm making sure to bind my function to this, but am getting a "Cannot read property 'onMouseEnterHandler' of undefined" error.

How am I not properly passing or binding this function?

class FeaturesContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
hovered: false
}
this.onMouseEnterHandler = this.onMouseEnterHandler.bind(this);
}
onMouseEnterHandler() {
this.setState({
hovered: true
})
console.log('mouse enter, ' + this.state.hovered);
}
render() {
return(
<div className="page features" >
<ul className="features-list">
{data.features.map(function(obj, i) {
return (
<li key={i}>
<Feature {...obj} onMouseEnterHandler={this.onMouseEnterHandler} />
</li>
)
})}
</ul>
</div>
)
}
}

class Feature extends React.Component {
render() {
var bgImg = {
backgroundImage: 'url(' + this.props.img + ')'
};
return (
<div className="feature-container" onMouseEnter={this.props.onMouseEnterHandler}>
<div style={bgImg} className="feature-img"></div>
<div className="feature">
<h4 className="feature-issue">Issue {this.props.issue}</h4>
<h1 className="feature-title">{this.props.title}</h1>
<h4 className="feature-copy">{this.props.copy}</h4>
</div>
</div>
)
}
}

Answer

this inside the .map callback is undefined. That's why you get an error when trying to access this.onMouseEnterHandler.

Either use an arrow function:

data.features.map((obj, i) => { ... })

or pass this as second argument to .map:

data.features.map(function(obj, i) { ... }, this)