This article is for developers new to frontend JavaScript. If you already know the basics, move on to best practices for AJAX with React.
React can be used with static data - but this gets boring preeeettty quickly. You might be left wondering:
How do I populate my React components with data from a server-side API?
The truth is, React is a view library and doesn't provide any networking capabilities. If this is news to you, go read about what react actually is, then head back here.
Since React has no networking features, passing server-side data to React is a 2-step process:
In this article, I'll walk you through the flow of data from the server to React. Let's start with the server.
The server provides data to your application via the internet.
The server could be a 3rd-party API like the GitHub API, or it could be your own server. For your own server you could use Rails, Django, Tomcat, the list goes on. Express is a common choice for React developers because it runs on Node.js.
The best format for transferring data from the server to the browser is JSON.
JSON is a text-based data format consisting of attribute–value pairs. It looks similar to JavaScript code.
Here's an example of some JSON:
{
"total_count": 47524,
"items": [
{
"name": "react",
"full_name": "facebook/react",
"owner": {
"login": "facebook"
},
"description":
"A declarative, efficient, and flexible JavaScript library for building user interfaces.",
"language": "JavaScript"
},
{
"name": "react-native",
"full_name": "facebook/react-native",
"owner": {
"login": "facebook"
},
"description": "A framework for building native apps with React.",
"language": "JavaScript"
}
]
}
Networking in client-side JavaScript is accomplished with AJAX.
AJAX stands for 'asynchronous javascript and xml'. For React developers this is a bit of a misnomer: JSON will be used much more commonly than XML.
Browsers make AJAX/network requests using the XMLHTTPRequest API
or the newer
Fetch API
. There are also many JavaScript libraries that wrap these APIs to
provide an easier-to-use interface for you, the developer.
For help deciding which AJAX library to use, read my AJAX library comparison.
Once you have the data from the server, you'll want to save it somewhere.
The data store could be Redux or another flux.
For simpler application, you could simply store your data in the state
of one
of your React components.
Once you have the data, adding it to React completes the picture.
Usually you would populate the data with props
. If you use
Redux or
Relay this will be done for you.
The above is a very general overview. To dive deeper, read the best practices for AJAX with React. In that article I help you decide how to use AJAX for your specific React project.