Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get state right after setState()

I know setState() does not immediately mutate this.state. So in the code below, checkbox is always unchecked after clicking the button. How to fix this?

handleClick = () => {
  this.setState({tick: !this.state.tick})
}

render() {
  return (
    <button type='button' onClick={() => this.handleClick()} >
      <input type="checkbox" value={this.state.tick} />
      Tick here
    </button>
  )
}
like image 548
lucahuy Avatar asked Mar 04 '23 21:03

lucahuy


1 Answers

use checked instead of value:

<input type="checkbox" checked={this.state.tick} />

from the spec:

checked: Boolean; if present, the checkbox is currently toggled on

value: The string to use as the value of the checkbox when submitting the form, if the checkbox is currently toggled on

like image 197
ic3b3rg Avatar answered Mar 17 '23 05:03

ic3b3rg