2

how to retrieve radio button selected value and name. I used the selectedOption and it only retrieve the value. Thanks. App.js

const tuitions=[
  {name:"In-state Resident", tuition: 1000, key:1 },
  {name:"Out-state Resident",tuition: 2000, key: 2}
];

class App extends Component {

  constructor(props){
    super(props);
    this.state={

    };
  }

  _RadioClickHandler=(event)=>{
    this.setState({
      selectedOption:event.target.value
    })
  }

  render() {
    return (
      <div className="App">
        <form>
         {tuitions.map(item=>(
           <RadioGroup 
             value={item.value} 
             key={item.key} 
             name={item.name} 
             onChange={this._RadioClickHandler.bind(this)}  
           />)
          )}
          <p>Display 
            <InstitutionList 
              selectedList={this.state.selectedList} 
              resident={this.state.selectedOption}
            />  
          </p>

//this.state.selectedOption only pass the value

RadioGroup.js

import React from 'react';

const radioGroup=(props)=>{
  return (
    <div>
      <input 
        type="radio"
        name="School"
        value={props.value}
        onChange={props.onChange}
      />
      {props.name}
    </div>
  );
}
export default radioGroup;

1 Answer 1

1

You can pass it to your change handler like so: onChange={e => this._RadioClickHandler (e, item.name) } Take a look at the snippet below to see it work:

const tuitions = [
  { value: 'ValueA', key: 'KeyA', name: 'Name A' },
  { value: 'ValueB', key: 'KeyB', name: 'Name B' },
  { value: 'ValueC', key: 'KeyC', name: 'Name C' }
];

const RadioButton = (props) => (
    <label>
      <input 
        type="radio"
        name="Schools"
        value={props.value}
        onChange={props.onChange}
      />
      {props.name}
    </label>
  );

class Thingy extends React.Component {
  _RadioClickHandler = (e, name) => {
    alert(`Value:${e.target.value}, Name:${name}`);
  }
  render() {
    return (
      <div>
        {tuitions.map(item=>(
           <RadioButton 
             value={item.value} 
             key={item.key} 
             name={item.name} 
             onChange={e => this._RadioClickHandler (e, item.name) }  
           />
           )
         )}
      </div>
    );
  }
}

// Render it
ReactDOM.render(
  <Thingy />,
  document.body
);
<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>
<div id="root"></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.