Home > Back-end >  How to get the selected radio button in React?
How to get the selected radio button in React?

Time:11-18

I'm looking for a way to get the selected button from a group of radio buttons.

For instance, how does it work in a code like this?

<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>

CodePudding user response:

In react, The function onChangeValue() is attached with div so as soon as the user selects any radio button, it will be reflected in the function.

When the user is done with the selection, they may want to submit the form. The submit method is called formSubmit().

 /*
 * A simple React component
 */
class App extends React.Component {
  constructor(params) {
     super(params) 
     // initial gender state set from props
     this.state = {
       gender: this.props.gender
     }
     this.setGender = this.setGender.bind(this)
  }
  
  setGender(e) {
    this.setState({
      gender: e.target.value
    })
  }
  
  render() {
    const {gender} = this.state
    return  <div>
        Gender:
        <div>
          <input type="radio" checked={gender == "male"} 
onClick={this.setGender} value="male" /> Male
          <input type="radio" checked={gender == "female"} 
onClick={this.setGender} value="female"  /> Female
        </div>
        { "Select Gender: " } {gender}
      </div>;
  }
}

/*
 * Render the above component into the div#app
 */
ReactDOM.render(<App gender="male" />, document.getElementById('app'));

 

CodePudding user response:

Try like this

Keep a handler function like this

const handleChange = (e) => {
    const { name, value } = e.target;
    alert(`${name} : ${value}`);
  };

And attach as a onChange handler.

<input
   type="radio"
   id="html"
   name="fav_language"
   value="HTML"
   onChange={handleChange}
/>

Code sandbox => https://codesandbox.io/s/distracted-moon-xi1co?file=/src/App.js

CodePudding user response:

Add an onChange handler to the parent element and, in that function, grab the id from the element that was clicked. Depending on your requirements you might then want to store that id in state.

Note I had to fix your HTML as the input and br elements were missing their closing tags.

const { useEffect, useState } = React;

function Example() {

  const [ selected, setSelected ] = useState('');

  // Destructure the id from the clicked element
  // and set the state with it
  function handleChange(e) {
    const { id } = e.target;
    setSelected(id);
  }

  // Log the state after its been updated
  useEffect(() => {
    if (selected) console.log(selected);
  }, [selected]);

  // Add handleChange as the handler for
  // the onChange listener
  return (
    <div onChange={handleChange}>
      <input type="radio" id="html" name="fav_language" value="HTML" />
      <label for="html">HTML</label><br/>
      <input type="radio" id="css" name="fav_language" value="CSS" />
      <label for="css">CSS</label><br/>
      <input type="radio" id="javascript" name="fav_language" value="JavaScript" />
      <label for="javascript">JavaScript</label>
    </div>
  );
};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related