How to Create a Real-time Bar Chart on React.js

What does in real-time mean

When an event or function is processed instantaneously, it is said to occur in real-time. To say something takes place in real-time is the same as saying it is happening "live" or "on-the-fly." For example, the graphics in a 3D action game are rendered in real-time by the computer's video card. You might have seen the use of a real-time scenario in a chat application and the likes.

In our tutorial, we are going to use React as a frontend framework. We will make use of a chart using react-chartjs-2 and chart.js package, which provides React components for easy chart integration (pie, bar, line e.t.c) into a React app. Mind you, we are using material UI for design.

We are going to simulate an API with a getData function and get it to show on our chart in real-time. You need to get the boilerplate/starter code ready.

Clone and run npm install to install the necessary dependencies.

It should look like the below when you run npm start

react real time chart starter.PNG

Great job if you see the above :)

Creating a Sample Dataset

We already have a set of data in the starter template, which is been consumed by our chart component. Next, we will reproduce a real-time experience.

Now we will create two (2) function getRandomInt and getData in App.js.

getRandomInt is a function that allows two (2) parameters and then returns a range between them.

const getRandomInt = (min, max) => {
  min = Math.ceil(min);
  max = Math.floor(max);

  return Math.floor(Math.random() * (max - min + 1)) + min;

getData generates an integer, then adds it to the array in the state while removing the first number in the array in 1.5seconds.

const getData = () => {
    setTimeout(() => {
      setData((prevData) => {
        const newData = [...prevData];
        const random = getRandomInt(100, 200);

        return newData;
    }, 1500);

What the useEffect hooks do is to call getData function when component mount and when data state changes

useEffect(() => {
}, [data]);


That's it. Full code here

No Comments Yet