Search code examples
reactjsthissetstate

How to send two parameters using one checkbox on its click event?


What I want to do is that when the user clicks on the checkbox, the corresponding companyid should be passed to the function where I can update its activation status. But I am not able to send 2 values in one method.

I have searched on various websites and still not able to get any results.

This is How I am printing companies:

{this.state.allCompanies.map(com => (
                <tr>
                 <td>{com.cname} </td>
                  <td>
                    <a>
                        <input
                          type="checkbox"
                          name="active"
                          checked={com.is_active == 1 ? "true" : ""}
                          onClick={this.handleActivated(this, com.cid)}
                        />
                    </a>
                  </td>
                </tr>

This is my handleActivated function:

handleActivated(e, id) {
    const active = e.target.name;
    console.log(e.target.value);
    console.log(e.target.checked);

    this.setState({
      active: e.target.checked
    });

    // this.setState({  });
  }

This is my state.

this.state = {
      allCompanies: [],
      data: false,
      company: "",
      active: ""
    };
    this.handleActivated = this.handleActivated.bind(this);

What I want is companyid in the handleActivated method.


Solution

  • Change onclick to this

    onClick={event=>this.handleActivated(event,com.cid)}
    

    Change your function to an arrow function

    handleActivated =(e, id)=> {
        const active = e.target.name;
        console.log(e.target.value);
        console.log(e.target.checked);
    
        this.setState({
          active: e.target.checked
        });
    
        // this.setState({  });
      }
    

    Once you do that , then you can remove this from constructor , because it is no longer needed.

    this.handleActivated = this.handleActivated.bind(this);
    

    This will give you more cleaner code