5

Before this is marked as duplicate I have searched and none of the answers seems to work for me.

My checkbox isn't working when changed, clicked, checked it whatever.

This is my component

class Checkbox extends React.Component{
  constructor(props) {
    super(props);
    this.state = {checked: false}
    this.handleCheck = this.handleCheck.bind(this);
  }
  this.handleCheck(e) {
    e.preventDefault();
    this.setState({
      checked: e.target.checked
    })
  }
  render() {
    return (
      <input type="checkbox" checked={this.state.checked} onChange={this.handleChecked}
    );
  }
}

Any reason why it shouldn't work?

3
  • 4
    e.preventDefault() fault? :) remove it! Commented Mar 2, 2018 at 22:29
  • you reference this.handleChecked in the onChange, but your method is named handleCheck Commented Mar 2, 2018 at 22:36
  • @Hamms, good catch! Commented Mar 2, 2018 at 22:37

1 Answer 1

7
import React from 'react';
import { render } from 'react-dom';

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = { checked: false }
    this.handleCheck = this.handleCheck.bind(this);
  }

  handleCheck(e){
   this.setState({
    checked: e.target.checked
   })
 }
render(){
  return (
    <div>
      <input
        id ="checkbox_id"
        type="checkbox"
        checked={this.state.checked}
        onChange={this.handleCheck}
      />
      <label htmlFor="checkbox_id"></label>
    </div>
   );
}
}

render(<Checkbox />, document.getElementById('root'));

Working Demo

Issues

  • Method should be initialised as handleCheck(e) not this.handleCheck(e)
  • There shouldn't be e.preventDefault()
  • onChange={this.handleCheck}
  • As you are using materializecss, you need to add an id in input and a label for this id.
Sign up to request clarification or add additional context in comments.

6 Comments

It works. But when I load my materialize css stylesheet it stops working. Any knowledge about that?
I think your css stylesheet override the style so that it doesn't look like checked. Can you share your css file?
I'm not loading any custom css. I'm using materialize css framework
In this case, you need a checkbox id and a label which is styled by materialise css. See my update.
I've figured it out. It's because of a class .input-field it's not supposed to be there
|

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.