Search code examples
javascriptreactjstypescripteventssemantic-ui-react

Change handler for semantic-ui-react checkbox does not work : React+Typescript


I am having two semantic-ui-react checkboxes. When I am trying to attach change handlers, I get a value of 'undefined' when I console log .

Want to fetch both of the checkbox values.

Link to the sandbox: https://codesandbox.io/s/5vo8v4996k

Where am I going wrong?

Help would be appreciated

import React from "react";

import ReactDOM from "react-dom";

import { Checkbox } from "semantic-ui-react";

import Form from 'semantic-ui-react/dist/commonjs/collections/Form';

export default class App extends React.Component<{},{}> {
  constructor(props:any) {
    super(props);
    this.state = {
      cb1: true,
      cb2: true
    };
  }

  checkboxChangeHandler = (event: React.FormEvent<HTMLInputElement>) => {
    let name = event.target.name;
    console.log(name); // It is giving undefined here
    if (name === "cb1") {
      this.setState({ cb1: !this.state.cb1 });
    }
    if (name === "cb2") {
      this.setState({ cb2: !this.state.cb2 });
    }
  };
  render() {
    return (
      <div >
       <Form>
        <Checkbox
          label={"CB1"}
          name="cb1"
          checked={this.state.cb1}
          onChange={this.checkboxChangeHandler}
        />
        <Checkbox
          label={"CB2"}
          checked={this.state.cb2}
          name="cb2"
          onChange={this.checkboxChangeHandler}
        />
       </Form>
      </div>
    );
  }
}

Solution

  • Got it working by using second param in callback, it contains all required information.

    checkboxChangeHandler = (event: React.FormEvent<HTMLInputElement>, data: any) => {
        this.setState({ [data.name]: value });
    };
    
    

    Working Sandbox: https://codesandbox.io/s/31oq13p3o1