Dennis Schaffer
Dennis Schaffer

Reputation: 620

How to handle radio Buttons with react.js

I'm building a React Component. This is a form, with a radio button, which can only be set to True and then no longer set back to false. I would like to be able to turn it on and off. And because worth read out.
What could the corresponding code look like? At the moment I have that:

import React, { Component } from 'react';

class Form extends Component {
art = {
selected: "uppper"
}
 onChange() {
console.log("Click")
 }
render() {
 return (
  <form onSubmit={this.handleFormSubmit}>
    <div>
      <label>
        <input type="radio" value="option1"
        onClick={this.onChange} />
        option1
      </label>
    </div>  
    <input type="submit" value="Submit" />
   </form>
   );
  }
 } 
export default Form;

Upvotes: 0

Views: 7570

Answers (2)

Cat_Enthusiast
Cat_Enthusiast

Reputation: 15688

while being consistent with using a class-component, your code would look something like this:

class Form extends Component {
  state = {
    selected: false
  };
  onChange = () => {
    this.setState({
      selected: !this.state.selected
    });
  };
  render() {
    return (
      <form onSubmit={this.handleFormSubmit}>
        <div>
          <label>
            <input
              type="radio"
              value="option1"
              onClick={this.onChange}
              checked={this.state.selected}
            />
            option1
          </label>
        </div>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
export default Form;

Essentially what you need are 3 things.

  1. A Boolean value in your state to keep track of the button was clicked (true or false).
  2. Give the input a checked property which matches the value of the selected state.
  3. Update the onChange handler to toggle the state value. Also ensure that the onChange handler is bound to the execution context by using an arrow function or binding the this keyword.

See working sandbox: https://codesandbox.io/s/mystifying-borg-gwl2q

Upvotes: 1

Colin Ricardo
Colin Ricardo

Reputation: 17239

Here's how you can do this:

import React, { useState } from 'react';
import { render } from 'react-dom';

const App = () => { 
  const [radioState, setRadioState] = useState(false);

  const handleChange = () => { 
    setRadioState(!radioState)
  }

  return (
    <input type="radio" checked={radioState} onClick={handleChange}/>
  )
}

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

Live example here.

Upvotes: 0

Related Questions