Friday, 22 January 2016

Loading external data in ReactJS

A quick example of how to load an external JSON file in React. This post assumes you have ReactJS already set up. I will be using Axios to load the external data, but you can use any library you wish. Axios is a promise-style Ajax tool with similar API to jquery.

For the external JSON data I have used the api from ’icndb’ which will load a JSON containing a Chuck Norris joke.

var React = require('react');
var ReactDOM = require('react-dom’);
var axios = require('axios');

var App = React.createClass({

    getInitialState: function() {
        return {joke:""}
    },
    
    componentDidMount: function() {
        var _this = this;
        axios.get("https://api.icndb.com/jokes/random").then(function(result) {
            _this.setState({joke: result.data.value.joke});
        });
    },

    render: function() {
        return <p>{this.state.joke}</p>
    }
});

ReactDOM.render(<App/>, document.getElementById('root'));
Here is the same example written in ES6.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';

class App extends Component{
  constructor(props){
    super(props);
    this.state = {
      joke:""
    }
  }

  componentDidMount(){
    axios.get("https://api.icndb.com/jokes/random").then((result) => {
        this.setState({joke: result.data.value.joke});
    });
  }

  render() {
      return <p>{this.state.joke}</p>
  }
}

Note, this is just purely an example of loading external data in React. It is generally bad practice to mix views with data fetching or manipulation - the two should stay separate.

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP