Mortezaipo Mortezaipo - 5 days ago 4x
React JSX Question

"this.state" or methods are not accessible in Reactjs

I have sample code to generate tree. But it shows errors that

is undefined while I've defined all of them in constructor.

export default class TreeList extends React.Component {
constructor(props) {
this.state = {tree: tree, action: null}
this.onClickNode = this.onClickNode.bind(this)
onClickNode(node) {
this.setState({active: node})
renderNode(node) {
return (
<span onClick={this.onClickNode(null, node)}>
render() {
return (
<Tree tree={this.state.tree} renderNode={this.renderNode}/>


I've used this library:


You need to bind this to your renderNode function because this is not automatically bound for ES6 classes. Otherwise, you will not have the appropriate context in your function. This is why your this.state.action is undefined and why it can't resolve this.onClickNode.

In your constructor, add

this.renderNode = this.renderNode.bind(this);

Also, if you want to use node in your onClick handler, you can switch it to

  onClickNode(firstParam, node) {
    return (event) => {
        this.setState({active: node})

I'm assuming that what's happening is that this.renderNode executes when render() is called which then is executing this.onClickNode and then updates the state. Well, since state is updated, it'll call render() again.