0

I have a Board Component which has a button in it. The button when clicked should trigger a handleClick function which will then call this.setState and update the state.

class Board extends React.Component {
constructor(props) {
    super(props);
    
    //temp_map is the connections namely left, bottom, right, top it has with other nodes
    let temp_map = new Map();
    temp_map.set('left', null);
    temp_map.set('bottom',null);
    temp_map.set('right', null);
    temp_map.set('top', null);

    this.state = {
        dots: Array(75).fill(temp_map)
    }

}

handleClick() {
    let temp_map = new Map();
    temp_map.set('left', null);
    temp_map.set('bottom',null);
    temp_map.set('right', null);
    temp_map.set('top', null);
    var dots = Array(75).fill(temp_map);
    dots[24]['left'] = 23;
    dots[23]['right'] = 24;
    
    this.setState();
    
}

renderSquare(i) {
    return (
        <Square index={i} connections={this.state.dots[i]}/>
    );
}

render() {
    return (
        <div className='board'>
            <button onClick={this.handleClick}> Click me</button>
            <div className='board-row'>
                {this.renderSquare(0)}
                {this.renderSquare(1)}
                {this.renderSquare(2)}
                {this.renderSquare(3)}
                {this.renderSquare(4)}
                {this.renderSquare(5)}
                {this.renderSquare(6)}
                {this.renderSquare(7)}
                {this.renderSquare(8)}
                {this.renderSquare(9)}
                {this.renderSquare(10)}
                {this.renderSquare(11)}
                {this.renderSquare(12)}
                {this.renderSquare(13)}
            </div>
        </div>
    );
}

}

But when I click on the button I get the following error:

Game.js:49 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at handleClick (Game.js:49:1)

in ES6, use can you use arrow function for function declaration to fix this issue. So I just wrote

handleClick = () => {
  ........

}

And it solved the problem. But I am still not able to understand why this solves the problem and what was actually the problem before when we were not using arrow function. Any help is highly appreciated.

Yuseff
  • 169
  • 4
  • 14

0 Answers0