React component ajax example

React ajax calls can be done in componentDidMount. Once we get the result, we can use setState to re-render the component. In case component can potentially unmount, we should clean any pending ajax calls in componentWillUnmount. You may also want to read React – Component Specs and Lifecycle.

Here is the code snippet:

<script src=""></script>
<script src=""></script>
<script src=""></script>
<script src="//"></script>

<div id="mycomp"></div>
<script type="text/babel">
var MyComp = React.createClass({
  getInitialState: function(){
    return {msg:  "-"};
  componentDidMount: function() {
    var obj = this;
    this.reqHandle = $.getJSON("/api/get-json-hello-world.php", function (data) {
      obj.setState({msg: data["msg"]});
  render: function() {
    return (<div>{this.state.msg}</div>);
  componentWillUnmount: function() {
ReactDOM.render(<MyComp/>, document.getElementById('mycomp') );

Few points to note

  1. The url /api/get-json-hello-world.php returns the following json object:

    {"msg":"Hello World"}
  2. jQuery getJSON automatically parsed the returned json.
  3. jQuery getJSON call returns a handle which can be used to abort the request later if needed.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments