Jack The Baker
Jack The Baker

Reputation: 1883

Why onchange function not working with semantic class

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?

Upvotes: 0

Views: 201

Answers (1)

makkBit
makkBit

Reputation: 393

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>
    )
  }

Upvotes: 1

Related Questions