3

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.

1 Answer 1

2

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')
);
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.