Random Color TypeScript Function

← Go Back Code Snippets
341 Words • ~2 Minute Reading Time
Random Color TypeScript Function by Eric David Smith

I use a lot of color in my projects. If you're looking for a simple function, don't install a package from NPM. Instead, first try to understand the problem, solution and of course the code before you reach for a new module.

A random color generator is a handy tool to have in your toolbox. Here's a simple function that returns a random color in TypeScript for use in React, Vue, Angular, or any other JavaScript project.

Simple Random Color Generator in TypeScript


export const randomColor = () => {
  const randomColor = Math.floor(Math.random() * 16777215).toString(16);
  return "#" + randomColor;
};

Better Random Color Generator in TypeScript


class ColorError extends Error {
  constructor(message?: string) {
    super(message);
    this.name = "ColorError";
  }
}

export const randomColor = (): string => {
  const randomColor: number = Math.floor(Math.random() * 16777215);
  const colorString: string = "#" + randomColor.toString(16);

  // Check if the color is a valid 6-digit hexadecimal color
  if (!/^#[0-9A-F]{6}$/i.test(colorString)) {
    throw new ColorError(`Invalid color generated: ${colorString}`);
  }

  return colorString;
};

Hooks for React


import { useState, useEffect } from "react";

const useRandomColor = () => {
  const [color, setColor] = useState<string>("#FFFFFF");

  useEffect(() => {
    try {
      setColor(randomColor());
    } catch (error) {
      if (error instanceof ColorError) {
        console.error(error.message);
      } else {
        throw error;
      }
    }
  }, []);

  return color;
};

export default useRandomColor;

Usage


import React from "react";
import useRandomColor from "./useRandomColor";

const ColorfulComponent: React.FC = () => {
  const color = useRandomColor();

  return <div style={{ backgroundColor: color }}>Hello, world!</div>;
};

export default ColorfulComponent;

That's It!


Hope you enjoyed reading my blog and learning how to use this simople random color function in TypeScript. If you have any questions, please feel free to reach out to me on Twitter or LinkedIn.

Supporting My Work


Please consider Buying Me A Coffee. I work hard to bring you my best content and any support would be greatly appreciated. Thank you for your support!


Eric David Smith
Father / Software Engineer / Musician / Entrepreneur

Discover More (3) Code Snippets


Blog Tags