THpubs
THpubs

Reputation: 8172

How to get the selected value from a radio button group in React where there are multiple groups?

I have a group of radio buttons like this :

return committees.map((committee) => {
  return (
    <div>
      <input type="radio" name={committee.shortName}
        ref={`${committee.shortName}Preference`} defaultChecked="true" value="1" />
      <label>1</label>
      <input type="radio" name={committee.shortName}
        ref={`${committee.shortName}Preference`} defaultChecked="true" value="2" />
      <label>1</label>
      <input type="radio" name={committee.shortName}
        ref={`${committee.shortName}Preference`} defaultChecked="true" value="3" />
      <label>1</label>
      <input type="radio" name={committee.shortName}
        ref={`${committee.shortName}Preference`} defaultChecked="true" value="4" />
      <label>1</label>
      <input type="radio" name={committee.shortName}
        ref={`${committee.shortName}Preference`} defaultChecked="true" value="5" />
      <label>1</label>
    </div>
  );
});

There are multiple groups like this in this page. React ref does not give me the right value. It gives the value as 5 (The last value) for all the groups. If I use getElementsByName it give me 5 elements (5 radio button fields). I need to get the selected value of the group. How can I do this?

Upvotes: 4

Views: 7460

Answers (2)

Andrea Korinski
Andrea Korinski

Reputation: 275

If you are using React I don't think it's a correct way to use it jQuery-style, using ref - React works nice as a final-state-machine and you should store your components data in state and do not request it accessing component by ref.

So you should add something like onChange= ()=>this.setState({selectedValue: 'yourValue'}) to pass correctly changed value to the state, and if you want to use "controlled" input value={this.state.selectedValue} or in the case with radio buttons checked={this.state.selectedValue === 'yourValue'}.

But you do not really need use radio checks and groups with react, you could do something like this:

committies.map(committie => (
  <button className={this.state.selectedValue === committie.id ? 'selected' : ''}
          onClick={() => this.setState({selectedValue: committie.id})}>
      {committee.shortName}
  </button>
))

Upvotes: 0

omerts
omerts

Reputation: 8848

You could keep an inner state with a map between commitee.shortName => selectedValue (updating the state onChange), and then add a:

checked={this.state.selectedValues[committee.shortName] === radioValue}

Here is a fiddle: Radio Buttons Example

There is also a library that sugars it off for you: react-radio-group

Upvotes: 3

Related Questions