MongoDB Charts Embedding SDK with React
Rate this tutorial
To add some spice in the mix, we will use our list of countries to create a dynamic filter so we can filter all the COVID-19 charts by country.
To run this project, you will need
npmin a recent version. Here is what I'm currently using:
You can run the project locally like so:
In the next sections of this blog post, I will explain what we need to do to make this project work.
Before we can actually embed our charts in our custom React website, we need to create them in MongoDB Charts.
To enable the filtering when I'm embedding my charts in my website, I must tell MongoDB Charts which field(s) I will be able to filter by, based on the fields available in my collection. Here, I chose to filter by a single field,
country, and I chose to enable the unauthenticated access for this public blog post (see below).
User Specified Filtersfield, I added
For each of the four charts, I need to retrieve the
Charts Base URL(unique for a dashboard) and the
Now that we have everything we need, we can go into the React code.
index.jsroot of the project is just calling the
Dashboardis the central piece of the project:
It's responsible for a few things:
- Lines 18-22 - Select a random country in the list for the initial value.
- Lines 22 & 26 - Update the filter when a new value is selected (randomly or manually).
- Line 32
counties.map(...)- Use the list of countries to build a list of radio buttons to update the filter.
- Line 32
<Charts .../> x4- Call the
Chartcomponent one time for each chart with the appropriate props, including the filter and the Chart ID.
As you may have noticed here, I'm using the same filter
fitlerCountryfor all the Charts, but nothing prevents me from using a custom filter for each Chart.
You may also have noticed a very minimalistic CSS file
Dashboard.css. Here it is:
Chartcomponent looks like this:
Chartcomponent isn't doing much. It's just responsible for rendering the Chart once when the page is loaded and reloading the chart if the filter is updated to display the correct data (thanks to React).
Note that the second useEffect (with the
chart.setFilter(filter)call) shouldn't be executed if the chart isn't done rendering. So it's protected by the
renderedstate that is only set to
trueonce the chart is rendered on the screen.
We also learned how to create dynamic filters for the charts using