vesperae vesperae - 6 months ago 37
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) {
this.state = {
hovered: false
this.onMouseEnterHandler = this.onMouseEnterHandler.bind(this);
onMouseEnterHandler() {
hovered: true
console.log('mouse enter, ' + this.state.hovered);
render() {
<div className="page features" >
<ul className="features-list">
{, i) {
return (
<li key={i}>
<Feature {...obj} onMouseEnterHandler={this.onMouseEnterHandler} />

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>


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:, i) => { ... })

or pass this as second argument to .map:, i) { ... }, this)