Eric  Bukenya

Eric Bukenya

1626306900

How to Create a Random Hex Colour Generator in React

If you’re looking for the source code, then it’s available in the video.

In this, we’re going to see how to create a full-screen hex colour generator that generates colours randomly.

We’ll create a separate component for generating this colour, and name it RandomColor.

useState

It is used to store the generated colour and also to update the colour on a button click. It’ll help us in updating the colour of the page reactively. 😏

getRgb

  • This function is used to get a random value. The range of this function is 0 to 255 (because RGB ranges from 0 to 255 🧐).
  • Math.random generates a floating-point value between 0 and 1. On multiplying with n, we will get the value in the range of 0 and n — 1.
  • But it’ll still be in decimal, so we can use Math.floorto get the floor round-off value.

rgbToHex

  • This function is used to generate the hex code of the colour based on the three values of **red, blue, **and green.
  • We are mapping over these 3 values and applying toString() function over the value. We can provide a radix argument to this function which converts the number as per the base value provided. Here, we are using **16 **which is for hexadecimal numbers because hex code colour is made up of hexadecimal numbers 🧐.
  • Then we are checking whether the length of the result is 1 or more, if it’s 1 then we’re adding **0 **in front of it to normalize it.
  • At last, we’re joining the array and adding a # in front of the generated string.

#programming #react #css #javascript #random

How to Create a Random Hex Colour Generator in React