moesh moesh - 1 year ago 217
React JSX Question

Uncaught TypeError: _this3.chooseTopic is not a function ReactJS

I am getting an issue using react, where I'm trying to click on a list item and invoke a method, chooseTopic, for the class but I'm getting returned "Uncaught TypeError: _this3.chooseTopic is not a function ReactJS"

Here is roughly my class:

class Topicselect extends Component {
constructor(props){
super(props);
this.state = {
topics: ['math','english','science']
}
}
chooseTopic(){
console.log('has been clicked')
}
render(){
const topics = this.state.topics.map(function(topic, i){
return(<li key={i} onClick={() => this.chooseTopic()}>{topic}
</li>)
})
return(
<div className="topicselect">
<ul>
<p onClick={()=> this.chooseTopic()}>hello world</p>
{topics}
</ul>
</div>
)
}
}

export default Topicselect;


when I clicked the hello world paragraph it invokes the function, however when I click the list items it gives me the error, Uncaught TypeError: _this3.chooseTopic is not a function ReactJS

any ideas?

Answer Source

That's because you're using a function for your Array#map callback. Use an arrow function:

const topics = this.state.topics.map((topic,  i) => {
  return (
    <li key={i} onClick={() => this.chooseTopic()}>
      {topic}
    </li>
  )
})

The reason is because, in a function expression, this won't refer to your component, it depends on how it's called. Since this isn't referring to the component, chooseTopic isn't found as a method thus the error. An arrow function does not bind this and thus refers to the this of the enclosing scope -- the component.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download