Search code examples
javascriptreactjssemantic-ui

onChange event issue with class component


I just want to get value from Radio component (checked or unchecked) in ui-semantic having following code:

  componentDidMount() {
    this.setState({
      startDate: moment()
        .subtract(30, 'days')
        .startOf('day'),
      endDate: moment().endOf('day'),
      isChecked: false,
    });
  }

Radio component:

<Radio toggle className="ongoing-checkbox"
  label="Show ongoing alerts"
  value={ !this.state.isChecked }
  onChange={e => this.selectOngoingAlerts(e)}></Radio>

and handler function:

selectOngoingAlerts = (e) => {
  this.setState(this.state.isChecked = true);
  const { householdAlerts } = this.props;
  console.log('checked', this.state.isChecked);
}

How to have a state of Radio component in selectOngoingAlerts function? I want to make different actions with respect whether radio is checked or unchecked.


Solution

  • You need to accept the data / checked value from the second argument of the onChange callback. You were trying to assign the value in setState as well which is wrong. do it like you do in your componentDidMount

    selectOngoingAlerts = (e, data) => {
      this.setState({isChecked: data});
    }
    

    Also update the radio component to just pass the callback to your handler, you dont need or want a lambda here..

    <Radio toggle className="ongoing-checkbox"
      label="Show ongoing alerts"
      value={ !this.state.isChecked }
      onChange={this.selectOngoingAlerts} />
    

    From the docs, the second argument is where the value is passed

    You should be referencing the Checkbox docs like I linked because the Radio is syntactic sugar for <Checkbox radio />

    Remember: setState is async, so you cannot console.log the value like you are trying to. Instead use a callback on setState if you really want to see its updated value, or just move your console.log to the render so you can see the value change on render cycles.