If you want to create visualizations or charts using Material-UI in React, you should use the “MUI X Charts” library. It is a fast and extensible library created by a Team at MIT for rendering charts relying on D3.js for data manipulation and SVG for rendering.
We will use the latest versions of each library and ensure that the components are reusable. Our final output will be in BarChart for covid data.
Here’s a step-by-step guide to creating a data visualization project with React, Vite, Material-UI, TanStack Query, Axios, and a free online API for COVID-19 data.
Step 1: Initialize a React project
Let’s use Vite’s React template to create a new React project with some boilerplate using the command below:
npm create vite@latest data-visualization -- --template react
Go inside the project folder:
cd data-visualization
Install the necessary dependencies using the command below:
npm install
Step 2: Installing third-party libraries
Let’s install MUI libraries for styling, axios for sending GET requests to API to fetch the data, MUI X Charts to display Bar Chart, and TanStack Query to fetch, query, and cache the data.
npm install axios @mui/material @emotion/react @emotion/styled @tanstack/react-query @mui/x-charts
Step 3: Create the project structure
Our project’s final structure looks like this:
src ├── components │ ├── ChartComponent.jsx │ ├── DataFetcher.jsx ├── hooks │ └── useFetchData.js ├── App.jsx └── main.jsx
Step 4: Create a custom hook
We will create a custom hook that uses the TanStack Query to fetch the data from an API. The TanStack Query accepts queryKey and queryFn and returns data, isLoading, and isError state variables.
Under the “src” folder, create a new folder called “hooks”.
Under the “hooks” folder, create a new file called “useFetchData.js” and add the code below:
// src/hooks/useFetchData.js import { useQuery } from '@tanstack/react-query'; import axios from 'axios'; const fetchCovidData = async () => { const response = await axios.get('https://disease.sh/v3/covid-19/countries'); return response.data; }; export const useFetchData = () => { return useQuery({ queryKey: ['covidData'], queryFn: fetchCovidData, refetchInterval: 60000, // Refetch every minute }); };
If you don’t know TanStack Query, check out TanStack Query in React article.
Step 5: Create components
Let’s create a new folder called the “components” folder under the “src” folder.
Inside the “components” folder, create a new file called “ChartComponent.jsx” and add the below code:
// src/components/ChartComponent.jsx import { BarChart } from "@mui/x-charts/BarChart"; import { Box, Typography } from "@mui/material"; // eslint-disable-next-line react/prop-types const ChartComponent = ({ data }) => { // eslint-disable-next-line react/prop-types const topCountries = data.slice(0, 10).sort((a, b) => b.cases - a.cases); return ( <Box sx={{ width: "100%", height: 400 }}> <Typography variant="h6" align="center" gutterBottom> Top 10 Countries by COVID-19 Cases </Typography> <BarChart xAxis={[ { scaleType: "band", data: topCountries.map((country) => country.country), }, ]} series={[{ data: topCountries.map((country) => country.cases) }]} width={600} height={300} /> </Box> ); }; export default ChartComponent;
To create a BarChart, import the BarChart component from @mui/x-charts.
The ChartComponent we created is a functional component that accepts data as a prop, and it uses arrow function syntax.
The logic is to display a bar chart of the top 10 countries by COVID-19 cases. It processes the data prop to extract and sort the top 10 countries, then uses @mui/x-charts to render a bar chart with the country names on the x-axis and the number of cases on the y-axis.
The <BarChart> component from @mui/x-charts accepts the below props:
- xAxis: It defines the x-axis with a band scale type and labels using the country names from the topCountries array.
- series: It defines the data series for the chart, using the number of cases from the topCountries array.
- width and height: It sets the dimensions of the bar chart.
Now, we need to create a component that consumes the useFetchData hook.
Since this component accepts the data as a prop, we need to provide data, and to do that, we need to create another component called “DataFetcher.jsx” and add the below code:
// src/components/DataFetcher.jsx import { useFetchData } from "../hooks/useFetchData"; import ChartComponent from "./ChartComponent"; import { CircularProgress, Box, Typography } from "@mui/material"; const DataFetcher = () => { const { data, isLoading, isError } = useFetchData(); if (isLoading) { return ( <Box display="flex" justifyContent="center" alignItems="center" height="100vh" > <CircularProgress /> </Box> ); } if (isError) { return ( <Box display="flex" justifyContent="center" alignItems="center" height="100vh" > <Typography color="error">Error fetching data</Typography> </Box> ); } return <ChartComponent data={data} />; }; export default DataFetcher;
So, the DataFetcher.jsx component acts as a parent component, and the ChartComponent.jsx component acts as a child component.
Step 6: Update the App.jsx
The App.jsx file is the root component. So, we need to configure and provide the query client to our React application, enabling data fetching and caching. Also, import the DataFetcher.jsx component that contains the main chart component.
// src/App.jsx import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { CssBaseline, Container, Typography } from "@mui/material"; import DataFetcher from "./components/DataFetcher"; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> <CssBaseline /> <Container maxWidth="md"> <Typography variant="h4" component="h1" gutterBottom align="center" sx={{ mt: 4 }} > COVID-19 Data Visualization </Typography> <DataFetcher /> </Container> </QueryClientProvider> ); } export default App;
Also, update the main entry point of our application, which is the “src/main.jsx” file:
// src/main.jsx import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App.jsx"; import { CssBaseline, ThemeProvider, createTheme } from "@mui/material"; const theme = createTheme(); ReactDOM.createRoot(document.getElementById("root")).render( <React.StrictMode> <ThemeProvider theme={theme}> <CssBaseline /> <App /> </ThemeProvider> </React.StrictMode> );
Save the file and start the development server using the command below:
npm run dev
You can see that on the x-axis, we are showing the country names and on the y-axis, we are showing the number of covid cases.