Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Material-UI checkbox onChange event does not fire

Trying to use Material UI checkbox. Pretty simple one might think? Well the checkbox doesn't toggle. Turns out the onChange event is not fired even internally to the component (I put logs in the node_modules package).

      <Checkbox
        checked={this.state.isTrue}
        onChange={e => {
          console.log(e.target.checked);
          this.setState({isTrue: e.target.checked});
        }} />

Pretty simple, right? But the console.log never fires. I can hack around it by putting an onClick event handler on the component and toggling the state manually, but that is silly. Anyone have a clue?

The API is at https://material-ui.com/api/checkbox/#checkbox. Not rocket science.

like image 987
see sharper Avatar asked Oct 30 '19 03:10

see sharper


Video Answer


2 Answers

In many cases, Material UI Checkbox onChange event is not working.

I suggest to save your time and use onClick event instead.

It will work always. Checkbox usually have a boolean value.

 <Checkbox
    checked={this.state.isTrue}
    onClick={() => this.setState({isTrue: !this.state.isTrue})}
 />
like image 58
egor.xyz Avatar answered Oct 23 '22 04:10

egor.xyz


The issue might come from the structure of your component as provided code is perfectly fine, here is a working exemple you can try on codesandbox.io.

Compare with your code and try to find differences, but isolating a specific element might be a good way to realise the issue might come from somewhere else.

import React, { Component } from "react";
import { render } from "react-dom";
import Checkbox from "material-ui/Checkbox";

class App extends Component {
  constructor() {
    super();
    this.state = {
      isTrue: false
    };
  }
  render() {
    return (
      <div>
        <Checkbox
          checked={this.state.isTrue}
          onChange={e => {
            console.log(e.target.checked);
            this.setState({ isTrue: e.target.checked });
          }}
        />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

like image 11
sebastienbarbier Avatar answered Oct 23 '22 04:10

sebastienbarbier