0

I'm using state to control my component, and I'm not sure what part of the following code is causing the code to button to freeze once checked. This is the constructor:

  constructor(props) {
    super(props);


    this.state = {

      firstName: '',
      
      inPerson: false,
      onlineMedium: true,
    };

  }

This function should handle change:

  handleFormChange = (event) => {
    const target = event.target;

 if (target.name === "inPerson" || target.name === "onlineMedium") {

      const value = !this.state[target.name]

      const name = target.name;
      this.setState({
        [name]: value
      });
    } 
else {
      const value = target.value;
      const name = target.name;

      this.setState({
        [name]: value
      });
    }
  }

This renders the component:

  render() {

    return (
      <>
        <label className="tutor-add-label">
          First name
        <input
            className="tutor-add-input"
            type="text"
            name="firstName"
            value={this.state.firstName}
            onChange={this.handleFormChange}
          />
        </label>
        <div className="medium">
          <input
            type="radio"
            id="online"
            name="onlineMedium"
            checked={this.state.onlineMedium}
            onChange={this.handleFormChange}
          />
          <label htmlFor="online">online</label>

          <input
            type="radio"
            id="person"
            name="inPerson"
            checked={this.state.inPerson}
            onChange={this.handleFormChange}
          />
          <label htmlFor="person">In person</label>
        </div>

      </>
    )
  }

Edit: As per the comment below, please let me know if there is another way to select/unselect radio that works better. I was following this http://react.tips/radio-buttons-in-react-16/

Update: It seems that the click doesn't happen (after the first click)for some reason. Does that seem to point in any direction?

E. Reiner
  • 83
  • 9

1 Answers1

0

This is what worked for me:

Changing the event handler from onChange to onClick and using the following to control state:

        if (target.name === "onlineMedium" || target.name === "inPerson") {
            if (event.target.checked && !this.state[target.name]) {
                this.setState({
                    [target.name]: true,
                })
            }
            else if (event.target.checked && this.state[target.name]) {
                this.setState({
                    [target.name]: false,
                })
            }

        }

Credit: it was inspired by this answer: https://stackoverflow.com/a/57147343/10813256

E. Reiner
  • 83
  • 9