populate select with datajson using React js
10,997
You need to call setState to actually update your view. Here's a workable version.
//json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc ase_id":"CTSTESTING","name":"CTS-Testing"}]
//using jquery to make a ajax call
var App = React.createClass({
getInitialState: function() {
return {
opts:[]
};
},
componentDidMount: function() {
var source="https://api.myjson.com/bins/3dbn8";
this.serverRequest = $.get(source, function (result) {
var arrTen = [];
for (var k = 0; k < result.length; k++) {
arrTen.push(<option key={result[k].companycase_id} value={result[k].companycase_id}> {result[k].name} </option>);
}
this.setState({
opts: arrTen
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
<select id='select1'>
{this.state.opts}
</select>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('root')
);
Author by
Southpaw
Updated on September 03, 2022Comments
-
Southpaw over 1 year
I'm trying to populate a select using React js, I'm using the example given on the react js docs(https://facebook.github.io/react/tips/initial-ajax.html) , which uses jquery to manage the ajax calling, I'm not able to make it work, so far i have this:
here the codepen : http://codepen.io/parlop/pen/jrXOWB
//json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc ase_id":"CTSTESTING","name":"CTS-Testing"}] //using jquery to make a ajax call var App = React.createClass({ getInitialState: function() { return { opts:[] }; }, componentDidMount: function() { var source="https://api.myjson.com/bins/3dbn8"; this.serverRequest = $.get(source, function (result) { var arrTen = result['']; for (var k = 0; k < ten.length; k++) { arrTen.push(<option key={opts[k]} value={ten[k].companycase_id}> {ten[k].name} </option>); } }.bind(this)); }, componentWillUnmount: function() { this.serverRequest.abort(); }, render: function() { return ( <div> <select id='select1'> {this.state.opts} </select> </div> ); } }); ReactDOM.render( <App />, document.getElementById('root') );
html
<div id="root"></div>
any idea how to make it works, thanks.