0

I using reactjs and semantic ui and want to call a OnChange function on input checkbox:

App.js

getChecked = (e) => {
    if(e.target.checked === true){
        this.setState({
            rent: '1'
        });
    } else {
        this.setState({
            rent: '0'
        });
    }
    console.log(e);
};

..

<Input onChange={this.getChecked} type="checkbox" name="isRent" id="isRent" value={this.state.rent}/>

This code working perfectly JSFiddle

But when I use checkbox class from semantic ui on this input, onChange function not working anymore JSFiddle

Before:

<input type="checkbox" onChange={this.getChecked}/>

After:

<div className="ui slider checkbox">
<input type="checkbox" onChange={this.getChecked}/>
</div>

Any idea for why it now working?

1
  • You are mixing jQuery with react, this line is messing it up $('.checkbox').checkbox(); probably jQuery adding its own handler to it and so ignoring you function. Don't use jQuery anymore! Commented Aug 18, 2019 at 20:51

1 Answer 1

1

This is because when semantic ui classes is applied, input get z-index value of -1. (try inspecting it).
So, now input never gets clicked, hence onChange function is not invoked.

What you could do this, make the checkbox controlled.

  state = { checked: false }
  toggle = () => this.setState(prevState => ({ checked: !prevState.checked }))

  render() {
    return (
      <div className="ui slider checkbox" onClick={this.toggle}>
        <input type="checkbox" checked={this.state.checked}/>
      </div>
    )
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.