Search code examples
javascriptreactjsantd

Uncaught TypeError: Cannot read property 'name' of undefined [antdesign - switch]


I want to use the event as callback in the antd's switch. I don't know how to get the value of this.state.game using event.

handleToggle = event => {
     this.setState({
         [event.target.name]: !this.state[event.target.name]
     });
};

   render() {
     return(
        <Switch 
            checkedChildren='on' 
            unCheckedChildren='off' 
            name='game' value={this.state.game} 
            onClick={this.handleToggle}
        />
    );
}

Solution

  • Switch onClick signature is:

    Function(checked: boolean, event: Event)
    

    So it should be:

    handleToggle = (_, event) => {
      this.setState({
        [event.target.name]: !this.state[event.target.name]
      });
    }
    

    i.e event is the second argument.