How to use radio buttons in ReactJS? How to use radio buttons in ReactJS? reactjs reactjs

How to use radio buttons in ReactJS?


Any changes to the rendering should be change via the state or props (react doc).

So here I register the event of the input, and then change the state, which will then trigger the render to show on the footer.

var SearchResult = React.createClass({  getInitialState: function () {    return {      site: '',      address: ''    };  },  onSiteChanged: function (e) {    this.setState({      site: e.currentTarget.value      });  },  onAddressChanged: function (e) {    this.setState({      address: e.currentTarget.value      });  },  render: function(){       var resultRows = this.props.data.map(function(result){           return (               <tbody>                    <tr>                        <td><input type="radio" name="site_name"                                    value={result.SITE_NAME}                                    checked={this.state.site === result.SITE_NAME}                                    onChange={this.onSiteChanged} />{result.SITE_NAME}</td>                        <td><input type="radio" name="address"                                    value={result.ADDRESS}                                     checked={this.state.address === result.ADDRESS}                                    onChange={this.onAddressChanged} />{result.ADDRESS}</td>                    </tr>               </tbody>           );       }, this);       return (           <table className="table">               <thead>                   <tr>                       <th>Name</th>                       <th>Address</th>                   </tr>               </thead>                {resultRows}               <tfoot>                   <tr>                       <td>chosen site name {this.state.site} </td>                       <td>chosen address {this.state.address} </td>                   </tr>               </tfoot>           </table>       );  }});

jsbin


Here is a simplest way of implementing radio buttons in react js.

class App extends React.Component {    setGender(event) {    console.log(event.target.value);  }    render() {    return (       <div onChange={this.setGender.bind(this)}>        <input type="radio" value="MALE" name="gender"/> Male        <input type="radio" value="FEMALE" name="gender"/> Female      </div>     )  }}ReactDOM.render(<App/>, document.getElementById('app'));
<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="app"></div>