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

Adding Random Colors

Dynamic colors can significantly enhance data visualization by making your charts more visually appealing and easier to interpret. In this tutorial, you’ll learn to add random colors to Chart.js components in React using the open-source just.randomColor library, while maintaining a clean and reusable code structure.


Why Use Open-Source Libraries?

Instead of reinventing the wheel, leveraging existing tools like just.randomColor saves time and effort. Open-source libraries are well-tested, often maintained by the community, and allow you to focus on integrating functionality rather than building it from scratch.


Step-by-Step Implementation

  1. Install the Library:
    Use npm to add just.randomColor to your project.

    npm install just-random-color --save
    
  2. Import and Use the Library:
    Integrate just.randomColor into your utility function for generating chart data.

    import randomColor from 'just-random-color';
    
    export function arrayToChart(array) {
        const formattedData = {
            labels: [],
            datasets: []
        };
        
        array.forEach(item => {
            const color = randomColor(); // Generate random color
            formattedData.datasets.push({
                label: item.label,
                data: item.data,
                backgroundColor: color.toCSS(), // Set color with opacity
                borderColor: color.toCSS(),
                borderWidth: 2
            });
            formattedData.labels.push(item.name);
        });
    
        return formattedData;
    }
    
  3. Adjust Colors Dynamically:
    Customize the generated colors by tweaking opacity or setting boundaries for the hues.

    color.setAlpha(0.5); // Adjust opacity for background color
    
  4. Update the Component:
    Refactor your Chart.js component to use the updated utility function.

    import { arrayToChart } from './utils/arrayToChart';
    
    const formattedData = arrayToChart(rawData);
    
  5. Test Your Implementation:
    Run your application to confirm that the chart displays with dynamic, vibrant colors.


Why Take This Approach?

By leveraging an open-source solution like just.randomColor, you:

  • Save development time.
  • Enhance visual appeal with customizable color palettes.
  • Maintain clean, reusable, and idiomatic JavaScript code.

🎓 Take your data visualization skills further with our full React Data Visualization Course.

Video Transcript

00:00While this lecture is about adding random colors using the
00:04just dot random color, it's not really the main topic.
00:07The main topic is connects
00:09to the one we had in the last lecture, the idea
00:12of componentizing
00:13or more accurately in the language of node modulizing
00:17or the language of NPM.
00:18More accurately. What we're trying to do is create packages
00:22that have just specifically what we need.
00:24Even if you're not gonna be publishing your modules,
00:27make sure to extract things out.
00:29So they are, they become reusable.
00:31And in this case you could ought
00:33to lean on the open source community
00:34'cause there's a lot of mini solutions available out there,
00:37just like this sample
00:39that we're gonna explore in this lecture.
00:42Alright, let's go ahead
00:43and solve our dilemma from the last lecture.
00:46And I just, uh, from the last chapter action, I just noticed
00:49that my ben, uh, how horrible I gave you such great scores,
00:53but they are not here.
00:55So let's try to see what's going on there
00:56before we even do anything else.
00:58And by the way, one thing that I could already know just
01:01because of its construct
01:02and unfortunately we didn't get any errors, is
01:04that the data's not being fed only for the first item.
01:07And in that case, I know
01:08that my problem must be somewhere here
01:12and it is somewhere
01:15where the data itself is put in.
01:17And I'll have your object dot item, which is incorrect
01:21because I need it to be object and no dots there.
01:24But instead of that set
01:25that like this, go ahead and save that.
01:28That should sort that out.
01:29Okay, so with that said, let's go ahead
01:31and fix our color issue.
01:33And to do that, I'm gonna also use a third party tool.
01:37Now there's a million different ways you could have done it,
01:39but the easiest is using something already ready for us.
01:42And to do that, I'm just gonna go and install it.
01:45This is not a, this is a node js in general script
01:49or a JavaScript idiomatic thing.
01:52'cause it really just does one thing.
01:53It creates a random color to be able to use it.
01:57I need to call NPM and install
01:59and I'm gonna need this to save it in our production
02:01because we're gonna be using it in the production.
02:04And I'm gonna install just random color, very cool name
02:08for a library or a package or a module in this case.
02:12So let's go ahead and install it.
02:13And while it's being installed,
02:14let's start setting up the code.
02:16So in a to CA two chart, I'm gonna need to load it up.
02:20So I'm gonna import random color from just,
02:25uh, random color.
02:28And once I have it imported, I could start working with it.
02:31Where do I wanna work with it? Really only in the initiator.
02:34Fun for loop.
02:36That is setting up all of our different data types.
02:39So let me go ahead here and just add one more property
02:41after our data source.
02:42And lemme call this color.
02:44And our color is literally just gonna be a new random color
02:48and you're more than welcome to check the documentation
02:50to see all the different things that you could do in it.
02:53But I'm just gonna go and fetch an R.
02:55Once I've set the, the random
02:56color, I'm gonna set it to be an
02:58RGBA color.
02:59And now I have a color. Beautiful.
03:02The next step that I'm gonna do is I'm gonna go ahead
03:05and start adding into our data source the different
03:08properties that I want it to have.
03:09So first of all, my data source.
03:11I wanted to have a background color, background color,
03:16and the background color I want it to be is gonna be
03:19that color we just got as CSS.
03:22So two CSS. And again, this is in their documentation.
03:26Again, I also want to have a, uh, background.
03:29I wanna also have a border color.
03:31And this time around I'm gonna also do that to CSS only.
03:36The difference is the co the background color.
03:38I'm gonna leave it with a full opacity in the background.
03:41While for our actual background color, I'm gonna first go
03:45to my color and I'm gonna ask for the value
03:47and set its alpha channel to be dot five.
03:50So it's gonna be 50% of its alpha channel.
03:53This was already set
03:55as a string, so I have nothing to worry.
03:56Now we'll set the next one and that should be good.
03:59And let me also just make sure that it has a border, um,
04:03width of let's say two.
04:06Let me just go ahead and set these together.
04:08It doesn't really matter, but just visually
04:10it's more pleasing to me.
04:12And if we go ahead
04:13and give it a shot, we should first start up our server
04:17n pm start.
04:20And once our server is running,
04:21hopefully we should have a variety
04:23of different colors once our application starts rendering.
04:28And we sure do. And we have your allot of different colors.
04:30And by the way, you could also set the different varieties
04:34of what colors you want it to be.
04:36And you could learn more about that on your documentation
04:41for just that random color.
04:44So in this lecture, we kind of like
04:47made a full circle on the topic
04:48that we talked about in the last lecture about modules
04:51by picking an open source simple module
04:54to implement a problem that we've had.
04:57In the next lecture, we're gonna continue down our path
04:59of creating our component
05:01where we're gonna clean up memory leaks
05:03that are in existence in our component
05:05that you're probably not aware of yet.

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!