0

I am working on a react project I am trying to checked checkbox using state in react, but Unable to do it After I checked checkbox using state. I need to change state using setState. For example If I have checked using state then when I click the checkbox, then it has to change its state to checked: false.

If I am not clear put a comment.

This is code

This is App.js

import React, { Component } from 'react';

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      checked: true
    }
  }


  render() {
    return (
      <div>
        <form>
          <div class="form-group form-check">
            <input  style ={{defaultChecked: this.state.checked}} type="checkbox" class="form-check-input" id="exampleCheck1" />
          </div>
        </form>
      </div>
    )
  }
}
3
  • 1
    have you tried checked attribute of <input> rather than style? Commented Jan 22, 2020 at 9:05
  • Hi @YevgenGorbunkov If I put checked attribute it will work fine but I am trying to this with state and setState. Commented Jan 22, 2020 at 9:07
  • Use onChange() event handler to do setState() Commented Jan 22, 2020 at 9:08

2 Answers 2

2
import React, { Component } from 'react';

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      checked: true
    }
  }


  render() {
    return (
      <div>
        <form>
          <div class="form-group form-check">
            <input onClick={()=>this.setState({checked:!this.state.checked})} checked={this.state.checked} style ={{defaultChecked: this.state.checked}} type="checkbox" class="form-check-input" id="exampleCheck1" />
          </div>
        </form>
      </div>
    )
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hello @Cruse, did you try this?
0
    return (
      <div>
        <form>
          <div class="form-group form-check">
            <input checked={this.state.checked} type="checkbox" class="form-check-input" id="exampleCheck1" />
          </div>
        </form>
      </div>
    )
  }

You can then add onClick() or onChange() to handle the setState.

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.