Cleaning up and Preparing for a Real Project

At this point you're probably wondering where this tutorial is going, so let me summarise where you are so far:

How to install Webpack, Babel and React for development with ES6.

How to create a basic React component and import it into an application.

How to write simple JSX to render content.

How to use props to give a component values.

How to render several elements at once.

How to handle events such as onClick.

How to use state, and how it differs from props.

How to loop over and render data in an array.

All this will begin to come together now: we're going to use an Ajax call to fetch data from GitHub. Well, technically it's Ajaj rather than Ajax, because GitHub provides JSON rather than XML, but still: it's our next big task. If you've never used Ajax before, it's just a way to fetch data remotely using the web browser.

I chose GitHub for this task because it has a flexible, interesting API that is open to the public – you don't need to register for an API key in order to use it. That being said, GitHub does have API limits in place when you access it for free, so if you intend to make heavy use of it you might want to get an API key.

In the terminal, quit Webpack Dev Server by pressing Ctrl+C and run this command:

npm install --save superagent

SuperAgent is a ridiculously lightweight Ajax client with clear, simple syntax that makes it easy to learn and use. We're going to replace this whole "Hello, Scott from Scotland!" thing with the results of an Ajax call to GitHub that will pull in a list of commits to the React project. This will require making quite a few changes, but it's almost all stuff you've seen before.

Note: when SuperAgent has finished installing, make sure you run webpack-dev-server again.

…then delete them all. We don't need people any more. While you're deleting stuff, go ahead and remove the import Chance from 'chance' line and the whole buttonClicked() method too; these aren't needed right now. Don't worry: all that stuff you learned will prove useful in an upcoming chapter, its just that for now we don't need it.

Instead, we're going to create some very simple initial state: an empty array of commits. This will be filled by SuperAgent when its Ajax call completes. So, where those lines in your constructor were just a moment ago, put this instead:

src/pages/Detail.js

this.state = { commits: [] };

As for the render() method, we're going to change the variable names but otherwise just print out static data – we'll fill in the specifics soon enough, don't worry. Change it to be this: