javascriptreactjssinglepage

How to gracefully render React.js Components with ajax


I am working on a React.js app and all pages have components with some data that is fetched from an API, the problem is that all pages look weird when they load because the hardcoded text and design elements load first and when data is fetched everything gets filled in. Is there common way to do this in single page apps or specifically in React.js so the pages don't look weird while loading?


Solution

  • We've recently had a similar problem and here is an outline of how we've approached it:

    1) Add a loading key to state and initially set it to true
    2) When the AJAX requests returns data, set loading to false
    3) In render() method return a loading indicator / spinner when loading is true

    Here is a demo: http://codepen.io/PiotrBerebecki/pen/ozaaPm and full code:

    class App extends React.Component {
      constructor() {
        super();
        this.state = {
          time: null,
          loading: true
        };
      }
    
      componentDidMount() {  
        axios.get(this.props.url)
          .then(response => {
            this.setState({
              time: response.data.time,
              loading: false
            });
          })
          .catch(error => {
            console.log(error);
          });
      }
    
      render() {
        let content;
    
        if (this.state.loading) {
          content = 'Loading...'
        } else {
          content = <p>Current time is: {this.state.time}</p>;
        }
    
        return (
          <div>
            {content}
          </div>
        );
      }
    }
    
    
    ReactDOM.render(
      <App url={"http://date.jsontest.com/"} />,  document.getElementById('content')
    );