How to set event handler in React sub-component
The problem is that you're creating the item nodes using an anonymous function, and inside that this
means the window
. The fix is to add .bind(this)
to the anonymous function.
var itemNodes = this.state.items.map(function (item) { return <li key={item}><a href='#' onClick={this.handleClick}>{item}</a></li>;}.bind(this));
Or create a copy of this
and use that instead:
var _this = this, itemNodes = this.state.items.map(function (item) { return <li key={item}><a href='#' onClick={_this.handleClick}>{item}</a></li>;})
As I can understand the specification of the task for "Anna", "Bob", "Cal, the solution can be the following (based on a react component and ES6):
import React, { Component } from "react"export default class CurrentSelection extends Component { constructor() { super() this.state = { index: 0 } this.list = ["Anna", "Bob", "Cal"] } listLi = list => { return list.map((item, index) => ( <li key={index}> <a name={item} href="#" onClick={e => this.onEvent(e, index)} > {item} </a> </li> )) } onEvent = (e, index) => { console.info("CurrentSelection->onEvent()", { [e.target.name]: index }) this.setState({ index }) } getCurrentSelection = () => { const { index } = this.state return this.list[index] } render() { return ( <div> <ul>{this.listLi(this.list)}</ul> <div>{this.getCurrentSelection()}</div> </div> ) }}