Build a Simple Website with React, Axios, and a REST API Built with MongoDB Atlas App Services
Rate this code example
At the end of this tutorial, you will have a basic React project capable of retrieving a list of countries through a REST API and displaying them on a web page.
In the next blog post, I will use this project as a starting point. The list of countries will become a filter for a bunch of charts built with MongoDB Charts that I will be able to import into a website using the
. The final result will be a COVID-19 dashboard which will be easy to filter by country.
Please check that your versions of
npxare close to my versions:
In the body of this blog post, I will step through how to build this app. If you don't want to follow along, and you prefer to jump to the final project, you can clone this repository from Github:
We now have a clean canvas for the next step.
Axios is a promise-based HTTP client for Node.js and the most famous HTTP client, as far as I know, with currently more than 14 million weekly downloads. We will use it to query our REST API and retrieve the list of countries to display.
The result from accessing this REST API is a JSON document that looks like this:
Now that we have everything we need to build our React website, let's code!
If you followed all the instructions so far, here is what your working folder should look like:
Let's now edit the contents of
public/index.html. Nothing really fancy compared to the original version that came with the sample application. I just removed what wasn't necessary.
The only thing that we need to notice in this file is the fact that we now have an empty
divwith an id
rootwhich we will use to inject our React content.
Let's create a new file
We are now injecting our React content into our website and the content will be what the new
RestExamplecomponent will render.
You can now start the project with the command:
There are a few things that are worth explaining here if you are new to React:
- Finally, our function component will render the returned content. The
countries.map()function iterates over the list of countries and transforms each of the strings into an
<li>tag to create an HTML unordered list.
The final website should look like this:
If you got confused at any point, and your app isn't working, just clone the final project:
In this blog post, you learned how to create a basic React website that uses Axios to retrieve data from a MongoDB Atlas Cluster using a REST API implemented with MongoDB Atlas App Services.
In the next blog post in this series, we'll extend this project so that we can integrate some charts from MongoDB Charts. We'll show COVID-19 data for a country and select which country we want to filter by. Stay tuned!