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

Modifying Styles and Setting Up Canvas in React

Modifying Styles and Setting Up Canvas in React

In this tutorial, we’ll explore how to add styles to React components and set up a canvas for creating charts. This foundation is essential for building interactive visualizations using Chart.js.


Understanding React’s Approach to Styles

Unlike traditional HTML, where CSS is often kept separate, React encourages a component-focused approach. This can include defining styles directly within the component. Inline styles in React are written as JavaScript objects, offering flexibility and simplicity for styling specific components.

For example, styles can be applied using the style attribute with curly braces:

<div style={{ width: '900px', height: '300px', backgroundColor: 'blue' }}>

Setting Up a Canvas Component

To use Chart.js, you’ll first need a <canvas> element. Here’s how to create a reusable Chart component in React:

  1. Create a Component File:
    In your project, create a components folder and add a new file, Chart.js.
  2. Define the Component:
    Import React and Chart.js, then define your component as follows:
    import React from 'react';
    
    export default class Chart extends React.Component {
        render() {
            return (
                <div style={{ width: 900, height: 300, backgroundColor: 'blue' }}>
                    <canvas id="chartCanvas"></canvas>
                </div>
            );
        }
    }
    
  3. Integrate into Your Main File:
    Import the Chart component into your main React file and render it:
    import React from 'react';
    import ReactDOM from 'react-dom';
    import Chart from './components/Chart';
    
    ReactDOM.render(<Chart />, document.getElementById('root'));
    

Why Use a Canvas for Chart.js?

Chart.js works seamlessly with HTML5’s <canvas> element, allowing precise control over chart rendering. The canvas can dynamically resize, making it ideal for responsive designs.


This tutorial sets the groundwork for integrating Chart.js with React. In the next steps, we’ll populate the canvas with data and configure Chart.js to render visually compelling charts.

To dive deeper into React and data visualization, check out the full course:
Learn more about React Data Visualization.

Still right In 2024:

Is this approach still valid in 2024?

Yes, but with some caveats and modernizations. Let's break it down:


1. Inline Styles in React

React's inline styles are still supported and often useful for quick or dynamic styling. However, the ecosystem has shifted towards CSS-in-JS libraries like Emotion, Styled Components, or even Tailwind CSS for managing styles more comprehensively.

  • Pros of Inline Styles:

    • Simple and scoped to the component.
    • Useful for dynamic styles based on props or state.
    • No additional dependencies.
  • Cons and Alternatives in 2024:

    • Lack of pseudoselector support (e.g., :hover, :focus).
    • No media queries or complex styling out of the box.
    • CSS-in-JS solutions like Emotion or Styled Components offer scoped styling while supporting complex rules.

For larger applications, using modern CSS-in-JS or even a utility-based CSS framework like Tailwind CSS is preferred for maintainability and developer productivity.


2. Using <canvas> for Chart.js

Chart.js is still a relevant and powerful library in 2024, especially for simple charting needs. However, depending on the use case, you might want to consider other libraries:

  • Why stick with Chart.js?

    • Lightweight and performant for small to medium datasets.
    • Mature ecosystem with consistent updates.
    • Easy integration with React using libraries like react-chartjs-2.
  • Modern Alternatives:

    • D3.js: Offers lower-level control for complex visualizations.
    • Recharts or Victory: Tailored specifically for React, these libraries provide reusable chart components and better React integration.
    • Apache ECharts: A highly customizable and performant charting library for large datasets.

If you're building an application that relies on complex visualizations or large datasets, you might benefit from exploring these alternatives.


3. Functional Components and Hooks

The example code uses a class-based React component, which is now considered somewhat outdated. Functional components with hooks have become the standard since React 16.8:

  • Modernizing the Example:
    Instead of a class component, the Chart component can be refactored into a functional one. For example:

    import React, { useRef, useEffect } from 'react';
    import Chart from 'chart.js/auto';
    
    const ChartComponent = () => {
        const canvasRef = useRef(null);
    
        useEffect(() => {
            const ctx = canvasRef.current.getContext('2d');
            new Chart(ctx, {
                type: 'bar',
                data: { /* chart data */ },
                options: { /* chart options */ },
            });
        }, []);
    
        return <canvas ref={canvasRef} style={{ width: 900, height: 300, backgroundColor: 'blue' }} />;
    };
    
    export default ChartComponent;
    
  • Benefits of Using Functional Components:

    • Cleaner, more concise code.
    • Better alignment with React's modern paradigm.
    • Hooks like useEffect and useState simplify side effects and state management.

Conclusion: The Modern Approach

  1. For Styles:

    • Use a CSS-in-JS solution like Emotion for scoped styling or Tailwind CSS for utility-based styling.
  2. For Charting:

    • Stick with Chart.js for simple needs but consider react-chartjs-2 for React integration or other libraries like Recharts for more React-native solutions.
  3. For React Components:

    • Prefer functional components with hooks over class-based components for new projects.

By modernizing your approach in these areas, your project will be more maintainable and aligned with current best practices.

Video Transcript

00:00Welcome back.
00:01So what we're gonna do in this lecture,
00:03we're gonna be talking about
00:04how you add styles to components.
00:07And really I'm just gonna say that generally speaking
00:10is when you're working with regular HTML,
00:12you're told all the time
00:13to separate your CSS from your HTML, from your code.
00:18Contrary to that, the react philosophy is bundle up
00:21components and make them simple for you to work with.
00:24So adding styles directly into your HTML in React is not
00:29a negative per se.
00:31It is actually almost even encouraged.
00:33And we're gonna take a look at how do you actually do
00:35that in React And in the process we're gonna set up a new
00:39canvas, which we're going to use for the creation
00:43of all the different charts using chart js.
00:47Alright, now that we have everything installed,
00:50or at least where we have everything there,
00:52let's just go ahead and note to start our file.
00:55And what I'm saying that everything is is installed.
00:58I'm really talking about our two new packages
01:02that we've added in, which was our package
01:05that is gonna enable us to load in CVS files
01:08as we're building out the application
01:10and the package chart js, which will enable us
01:13to create charts.
01:14So with that said, let's go into our client
01:16and start building out and configuring out our logic.
01:20Or how about, let's start with a component
01:22and I already created a components folder
01:24and in it I want to create a file
01:26and let's call this chart js
01:29because we're gonna have your sending that will be able
01:32to be basically any chart theoretically speaking at least.
01:36Okay, so now with that said,
01:37what do we need for our chart to do?
01:39So first of all, we're gonna need to import React from
01:44React just like always.
01:46We're gonna need to import our chart
01:51from um, chart js.
01:55And really because we are naming our package chart,
01:57let's go ahead and just call this chart js
02:00so it's very clear the difference, well not that clear,
02:03but clear for us at least, export default
02:08class chart extends
02:14react component.
02:17Beautiful. And let's go ahead and do a render.
02:19Now our render function
02:21and we're really just doing our first steps here
02:24in our render function.
02:25What I'm gonna do, I'm gonna return uh, canvas.
02:29The reason is, is because charge js expects a canvas.
02:34Now I'm gonna go ahead
02:35and I'm not gonna set a width and high to it.
02:38And the reason is, is
02:39because it really doesn't matter what's what, width
02:42or height I'm gonna give it
02:43because React will automatically not react,
02:47actually charge will automatically resize
02:49and try to get it to be in the most,
02:51the biggest zone that it can.
02:53Now, if we wanted to undo that
02:55and control, give it a little bit of control over
02:59The levels of where it could, uh,
03:00or how big it could go to, um, a very good way of doing
03:04that is just setting a diviv layer above it
03:06and giving it a style rule.
03:08Now styles in React,
03:12I could literally just send an object into the style itself.
03:15So if this, the first curly bracket was
03:18to let us let everyone know that we have a object, we're,
03:21we're putting here a reference
03:22and inside I'm building out a variable.
03:24So for example, I wanna set the width to be 900.
03:28Let's say I want my height
03:31to be 300 let's say.
03:34And how about we'll also set a background color
03:37and we'll set that to be blue.
03:40And lemme go ahead here and just put here a little bit
03:42of a word wrap and lemme go ahead and save this.
03:46Okay, so that's gonna be our component,
03:47our starting point component.
03:49Let's go into our client and actually pull it
03:51in and actually use it.
03:52So to do that again, I'm gonna have to grab out that import.
03:57So let me just copy that and use it again.
03:59We're gonna definitely need the react.
04:01We're also gonna need react dumb.
04:05And we're also gonna need our chart.
04:07So it's called chart, it's positioned inside of our
04:12components folder and it's called Chart.
04:16Uh, think that's all we need. Now.
04:18We could go ahead and delete that and let's give it a run
04:21and try react.
04:22Dom Render, what are we rendering chart
04:27for now, we're not gonna send anything into it
04:29and I'm gonna go ahead and define our document,
04:33get L element by ID
04:36and send it to our React, which is uh, ID element inside
04:40of our HTML.
04:41Now if everything is working, we shouldn't really see much,
04:45but we should see something here which is basically just
04:47gonna be our canvas size that we configured.
04:50Beautiful. So we're already in a fantastic starting point
04:54and the next lecture we'll continue into integrating the
04:57actual React chart itself and start working with it
05:02and understand where do we actually put it, if we have
05:04to configure and set that canvas in advance.
05:07And then how do we influence it once it's already configured
05:11In this lecture we explored styles and set up our canvas.
05:16And the next one we'll continue preparing our chart data
05:19for the chart that we're going to be creating really soon.
05:22I.

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!