Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the value of Radio button(react-radio-buttons) in Reactjs?

How do I get the value of radio buttons , if I call updateRadioButton in RadioGroup, it results in error. I need to print as Male or Female in console using (react-radio-buttons). Radio Buttons are printing correctly but I'm unable to get the value. Thank you in Advance.

 class CreateUserComponent extends React.Component {
        constructor(props) {
        super(props); 
        this.state={radio:''}
    }

    updateRadioButton(e) {
        this.setState({ radio: e.target.value });
    }

    <RadioGroup horizontal>
            <RadioButton value="Male">Male</RadioButton>
            <RadioButton value="Female">Female</RadioButton>
        </RadioGroup>
like image 204
PremKumar Avatar asked Sep 02 '25 02:09

PremKumar


2 Answers

Well according to the DOCS of this lib, RadioGroup has a onChange prop handler that you can pass that will return the selected value, and then you could set it in the state or pass it on.

Here is small running example with your code:

debugger
const RadioGroup = ReactRadioButtonsGroup.ReactRadioButtonsGroup;
const RadioButton = ReactRadioButtonsGroup.ReactRadioButton;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  onRadiochange = value => {
    console.log(value);
  };

  render() {
    return (
      <div>
        <RadioGroup horizontal onChange={this.onRadiochange}>
          <RadioButton value="Male">Male</RadioButton>
          <RadioButton value="Female">Female</RadioButton>
        </RadioGroup>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/bundle.min.js"></script>
<div id="root"></div>
like image 180
Sagiv b.g Avatar answered Sep 04 '25 21:09

Sagiv b.g


From this react-radio-buttons example:

class CreateUserComponent extends React.Component {
  ... 
  updateRadioButton(value) {
    this.setState({ radio: value });
  }

  render() {
    ...

    return (
      <RadioGroup horizontal onChange={this.updateRadioButton} >
        <RadioButton value="Male">Male</RadioButton>
        <RadioButton value="Female">Female</RadioButton>
      </RadioGroup>
    )
    ...
  }
}
like image 34
An Nguyen Avatar answered Sep 04 '25 22:09

An Nguyen