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="https://fb.me/react-0.14.7.js"></script> <script src="https://fb.me/react-dom-0.14.7.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></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() { this.reqHandle.abort(); } }); ReactDOM.render(<MyComp/>, document.getElementById('mycomp') ); </script>
Few points to note
-
The url /api/get-json-hello-world.php returns the following json object:
{"msg":"Hello World"}
- jQuery getJSON automatically parsed the returned json.
- jQuery getJSON call returns a handle which can be used to abort the request later if needed.