02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Creating a Bar Chart with ChartJS

Creating a Bar Chart with ChartJS in React

In this lesson, you’ll learn how to integrate Chart.js with React to create a dynamic bar chart. We’ll explore how to use React’s componentDidMount lifecycle method to manage rendering and how to dynamically pass data and options.


The React Way and DOM Manipulation

React separates rendering logic (ReactDOM) from component logic (React). This modularity minimizes direct DOM manipulation, which can slow down JavaScript applications. However, when working with Chart.js, direct canvas manipulation is necessary. Here’s how we work around React’s rendering model:

  1. Using componentDidMount:
    This lifecycle method ensures your canvas is accessible after the component renders. You can then safely manipulate the canvas for Chart.js.

Steps to Render a Chart

  1. Set Up a Canvas Reference:
    Use the ref attribute to give your canvas a reference name.
    Example:

    <canvas ref="chartCanvas"></canvas>
    
  2. Access the Canvas in componentDidMount:
    Use the ref to fetch the canvas context for Chart.js:

    componentDidMount() {
        const ctx = this.refs.chartCanvas.getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: this.props.data,
            options: this.props.options,
        });
    }
    
  3. Pass Data and Options via Props:
    Send chart type, data, and options as props for a reusable, configurable component.


Why Use componentDidMount?

React delays DOM updates for performance optimization. By using componentDidMount, you ensure the canvas exists before trying to manipulate it. This approach aligns with React’s lifecycle while allowing Chart.js to function as expected.


Common Errors and Fixes

  1. Accessing the Canvas Prematurely:
    If you try to manipulate the canvas before it’s mounted, Chart.js will throw an error. Use componentDidMount for timing.

  2. Data Format Issues:
    Ensure datasets are correctly formatted with datasets (plural) and arrays for labels and data.

  3. Chart Overwrites:
    Without cleanup, rendering the chart multiple times can create memory leaks. Address this in the cleanup phase (e.g., componentWillUnmount).


Conclusion

By combining React’s lifecycle methods with Chart.js’s canvas manipulation, you’ve successfully created a dynamic bar chart. In the next lesson, we’ll format external data from a CSV file and connect it to our chart for a real-world use case.

In 2024:

In 2024, React’s modern approach has shifted toward functional components and React hooks, particularly using useRef and useEffect, which replace class-based lifecycle methods like componentDidMount. Here’s how you can achieve the same functionality in a more modern React setup:


Using Functional Components and Hooks to Create a Bar Chart

Functional components with hooks provide a cleaner, more concise way to manage DOM manipulation. Here’s the modern equivalent of rendering a bar chart using Chart.js.


Step 1: Set Up Your Component

Use the useRef hook to reference the canvas and the useEffect hook to handle component lifecycle events.

import React, { useRef, useEffect } from 'react';
import Chart from 'chart.js/auto';

const BarChart = ({ data, options, type = 'bar' }) => {
  const canvasRef = useRef(null);

  useEffect(() => {
    // Access the canvas element and initialize the chart
    const ctx = canvasRef.current.getContext('2d');
    const chart = new Chart(ctx, {
      type,
      data,
      options,
    });

    // Cleanup function to destroy the chart on component unmount
    return () => {
      chart.destroy();
    };
  }, [data, options, type]); // Dependencies trigger re-render if props change

  return <canvas ref={canvasRef}></canvas>;
};

export default BarChart;

Step 2: Pass Data and Options as Props

In this functional approach, the chart configuration is passed as props, ensuring the component remains reusable and flexible. Here’s an example of how to use the BarChart component:

import React from 'react';
import BarChart from './BarChart';

const App = () => {
  const data = {
    labels: ['Ben', 'James', 'Mary', 'Sam', 'Gloria'],
    datasets: [
      {
        label: 'Fun Level',
        data: [90, 40, 30, 80, 100],
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgba(255, 99, 132, 1)',
        borderWidth: 1,
      },
      {
        label: 'Smart Level',
        data: [95, 30, 90, 85, 70],
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderColor: 'rgba(54, 162, 235, 1)',
        borderWidth: 1,
      },
    ],
  };

  const options = {
    responsive: true,
    plugins: {
      legend: {
        display: true,
        position: 'top',
      },
    },
  };

  return (
    <div>
      <h1>Bar Chart Example</h1>
      <BarChart data={data} options={options} />
    </div>
  );
};

export default App;

Why This Approach is Better in 2024

  1. Hooks and Functional Components:

    • Hooks (useRef, useEffect) simplify the lifecycle management and are now the React standard.
    • Functional components reduce boilerplate compared to class components.
  2. Chart.js/Auto:

    • Newer Chart.js versions, like chart.js/auto, simplify imports by automatically registering required components.
  3. Code Readability:

    • Functional components are more compact and declarative, aligning better with modern JavaScript practices.
  4. Dynamic Updates:

    • By including data, options, and type in the dependency array of useEffect, the chart automatically re-renders when props change.
  5. Cleanup with Hooks:

    • The chart.destroy() call in the return of useEffect prevents memory leaks and ensures proper cleanup.

Considerations for Further Modernization

  • Server-Side Rendering (SSR): If you’re using SSR frameworks like Next.js, ensure that the chart renders only on the client-side by checking the window object or using dynamic imports (next/dynamic).
  • Improved Styling: Use CSS-in-JS solutions like Emotion or Styled-Components for modern and scoped styling.
  • Data Fetching: Leverage React Query, SWR, or fetch APIs to load data dynamically instead of hardcoding data.

Conclusion

The functional component approach is cleaner, more concise, and leverages React’s modern features, making it better aligned with today’s best practices for React development in 2024.

Video Transcript

00:01Before we jump into this lecture
00:02and see how to connect our data
00:04and create our bar chart within React, I want
00:08to talk a little bit about the React way.
00:11Now, generally speaking, we already saw
00:14that we have the React component, the React Library,
00:16and the React DOM library.
00:19While the React was in charge of our components,
00:21the React dom was in charge of the communication
00:24with the browser itself.
00:26This separation was done very, very for a very good reason
00:31for one, to enable them to create different components,
00:34different rendering engines
00:36for different environments without changing our code.
00:39But secondarily, and one of the more important reasons is
00:42because when we manipulate the DOM directly,
00:46it creates a lot of overhead
00:47and this is really where the slowness of JavaScript lives.
00:50So by separating these steps,
00:52it's actually making our JavaScript a lot smarter
00:54because it's not gonna be rendering as soon
00:57as we request it.
00:58And that really moves us to our problem where when we render
01:02an element, it's not actually rendered as soon
01:04as we ask it to render.
01:06That happens behind the hood when React
01:08is ready to render it.
01:10So to be able to solve that problem,
01:12because that is a problem for us, for us
01:14to create our chart, we need access to the canvas
01:17that we've created that currently we wouldn't have within
01:20the component to solve that problem, we're going
01:22to use the component did Mount method, which is a callback
01:26that is called once the component is actually on the screen.
01:30With that said, this is specifically only a solution for a
01:35solution that is actually to the string,
01:37to the screen for that matter.
01:39React dom is good,
01:40but if we were working with React dom server, well that
01:44function would never be called.
01:45And thus our component is now tied to only components
01:50that are living within a React environment
01:53that is running on an actual client side implementation.
01:58With that said, let's take a look at
02:00how do we get it up and running.
02:04Okay. It's time for us
02:05to actually move from the client into our component area
02:09itself and start rendering out.
02:11Now for create for chart js to be able to gain access
02:15to our canvas, it actually needs the canvas
02:18to already be on the stage.
02:20So to do that, what we're gonna do is we're gonna add
02:22another built-in method
02:24that exists within any React component and override it.
02:28And I'm gonna call the component component.
02:32Did mount for our component, did mount function.
02:37What I want to do is I wanna make basically
02:40additional changes
02:41or modifications to our canvas now as our canvas itself for
02:46reacts purpose is really just never changing.
02:49All I really need is to gain access to it, to be able
02:52to draw inside of it.
02:54Now that's exactly what Chart JS does.
02:56So in this case, what I'm gonna go ahead and I'm gonna call
02:58That Canvas and to be able to gain access to that canvas,
03:02I need to give it a reference.
03:04So literally what I'm gonna do is I'm gonna call a ref
03:07and just give it a name.
03:08In this case, I'm just gonna call it Chart.
03:11Now that it has a name inside of my inside
03:13of my component did Mount, I could literally fetch it
03:16and get it the way I do that.
03:18And I'm just gonna go ahead and create here a new cons.
03:20Now that we know what cons are,
03:22and I'm gonna gain the context, I'm going ask from this refs
03:29the actual chart, and then I'm gonna get the context,
03:34which is 2D, which this is already all
03:38standard JavaScript stuff where I'm gonna get the context
03:41of our chart itself in 2D, which is
03:45what our chart expects for.
03:47Now that I have that information, I could go
03:49through the next step and the next step is I also want
03:52to gain access to a few more properties.
03:55And by the way, I want to gain the properties of type
03:58DA data and options
04:00that I've sent in from the client itself.
04:03Remember the type data and options.
04:06So how do I gain that A,
04:07that access I could use another cons
04:09or just for the sake of practice,
04:11let's create a let instead of that.
04:13And it's really cool.
04:14This is, uh, one of my favorite new features in E ES six
04:18where I could literally just type a list of the things
04:20that I want to grab out of an object.
04:23It's called to transcribe, I think,
04:26or trans, trans, something doesn't really matter,
04:29but you actually set the names of the properties
04:31that you want and then set the equal sign
04:33to the actual object that you wanna break apart
04:36and rip out of it the type data and options.
04:39And it will automatically just fetch those three
04:41that we need, which is really convenient for us
04:44because what we're gonna do next is I'm gonna go ahead
04:47and create here a chart.
04:48I'm gonna give it a reference so I could have access
04:51to it again in the next chapter
04:53because we're gonna continue
04:54with the sample in the next chapter
04:56and talk about how do we clean things up
04:58and make sure that our chart doesn't override itself over
05:01and over and over and over.
05:03Um, making it break, which is not a good thing
05:05or create a memory leak, which is not a good thing as well.
05:08But we're not gonna deal with that now.
05:10We're gonna deal with that in the next chapter.
05:12In this chapter, I want
05:13to just create the actual chart itself.
05:15And the first property it expects is that context.
05:19And the second property will be an object that will store
05:22inside a type, which is type, we'll store a data type,
05:26which in our case is data because we fetched it
05:29and options, which in our case is options
05:32as well, conveniently.
05:34And that's really all we had to do
05:37to get our chart to actually run.
05:39And if we go ahead and give it a shot
05:41and we don't have an error,
05:44but we don't have an error, oh,
05:46this blue is blocking everything probably,
05:48let's go ahead and get rid of it.
05:50Well, I don't think it is or, or, or, or,
05:54or that I'm not typing here something correctly.
05:56So maybe compo, let me just go ahead here and just set here.
06:00Uh, let's, oh, new chart. There you go.
06:03I'm basically creating it inside of myself.
06:05You see, I told you that I, the name
06:06that we picked was a really bad name.
06:08So let me go ahead and I'm setting it to charts
06:10'cause that's the library, not anything else.
06:12So I had nothing to do with the color,
06:13but we don't need that color anymore.
06:15And let's go ahead and give it another shot. Um, so good.
06:18We're starting to get errors, which is already good
06:20'cause we're, so it's, first of all, it's telling me
06:22that it can't find the data set inside of data.
06:25So let's go and see if, do we have a data set?
06:28Maybe we have a typo in the word data set.
06:32That looks to me so brilliantly
06:35fine data set.
06:38Let's see what it's actually saying here.
06:42No, this is just like, uh,
06:43while we're compiling stuff, so that's fine.
06:45This is really what's concerning us, that it's the data that
06:49data, oh, dataset, plural, not single.
06:53So it's data sets, data sets.
06:56Save that baby and let's go ahead
06:59and take a look and beautiful.
07:02We finally have a chart and it's running.
07:04And by the way, it's a little bit too big.
07:05So let's go ahead here and just make it slightly smaller
07:08by setting my height to be 250, let's say.
07:13And maybe my width will be 800.
07:15And once we re-render, our chart should be a tad smaller,
07:20which is working for us now.
07:23And we have ourselves a beautiful chart.
07:25Now we're far from done with working with charts.
07:28As you notice, we are just starting
07:29to explore this wonderful world of data visualization.
07:33But in the next lecture,
07:35what we're gonna do is we're gonna revisit our data source
07:37and make it external, which is gonna be a little bit more
07:40tricky because we are gonna use a CVS file
07:44to replace the actual content that we created in the client
07:47and then try to figure out how do we build this content out
07:50so it'll actually match up to the structure that it expects.
07:55Okay, in this lecture we saw
07:59and understood that limitation of the render method
08:02and saw how to implement
08:04and integrate our React component using component
08:08did mount method.
08:10In the next lecture, we're gonna go ahead
08:12and format our data
08:14and prepare it for an even more complex structure.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!