Curious Coding Adventures of a Developer

Curious Coding Adventures of a Developer

Generate Random Avatars in React

Generate Random Avatars in React

Funky & Sophisticated Random Avatar Generation APIs

Who doesn't love mock data generators? Tools like Mockapi or the all time favourite Faker open source library which recently gave birth to FakerCloud.

Those platforms provide ways to generate many API properties from simple things like e-mail or username to complex passwords and geocoordinates.

image.png

Today I'm gonna showcase some popular APIs/libraries to generate avatar images for your next React project.

1. FakerJS

Probably the greatest mock data generation library out there supporting many languages from PHP to JS and Python, it's API covers every possible use-case including images for animals, or avatars.

Let's install the faker JS package:

npm install faker
// or
yarn add faker

It's pretty straighforward to generate an avatar image like this:

import faker from "faker";

export const generateFakerAvatar = () => faker.image.avatar();
export const generateFakerAnimal = () => faker.image.animals();

2. Unsplash

image.png

Unsplash is an amazing platform showcasing beautiful, freely-usable images which we can use in design mockups or even final products depending on the given license of course.

We can also use the Unsplash Source API for basic tasks like fetching images of a certain user or by a certain query which suits our simple example.

export const generateUnsplashImage = (query) =>
  `https://source.unsplash.com/random/200x200/?${query ?? "avatar"}`;

If you are interested in the official Unsplash API which gives full control over more of the data managed by the platform you can register as a developer here.

3. Big Heads

image.png

The previous 2 examples bring real world avatar images but what if we want a cartoonish style to the avatars?

Here comes big heads with a stylized cartoon look and many variants for generating funky heads, the only downside is the lack of a direct random API (or at least I couldn't find one).

We install the library as usual

npm install @bigheads/core --save
// or
yarn add @bigheads/core

In order to generate random avatars we need to be able to mix random properties accepted by the BigHead component, thankfully after searching a tad bit through the official docs I managed to find this method:

// thanks to official https://github.com/RobertBroersma/bigheads/blob/main/site/src/utils/getRandomOptions.ts
import {
  theme,
  eyesMap,
  eyebrowsMap,
  mouthsMap,
  hairMap,
  facialHairMap,
  clothingMap,
  accessoryMap,
  graphicsMap,
  hatMap,
  bodyMap
} from "@bigheads/core";

function selectRandomKey(object) {
  return Object.keys(object)[
    Math.floor(Math.random() * Object.keys(object).length)
  ];
}

export function getRandomOptions() {
  const skinTone = selectRandomKey(theme.colors.skin);
  const eyes = selectRandomKey(eyesMap);
  const eyebrows = selectRandomKey(eyebrowsMap);
  const mouth = selectRandomKey(mouthsMap);
  const hair = selectRandomKey(hairMap);
  const facialHair = selectRandomKey(facialHairMap);
  const clothing = selectRandomKey(clothingMap);
  const accessory = selectRandomKey(accessoryMap);
  const graphic = selectRandomKey(graphicsMap);
  const hat = selectRandomKey(hatMap);
  const body = selectRandomKey(bodyMap);

  const hairColor = selectRandomKey(theme.colors.hair);
  const clothingColor = selectRandomKey(theme.colors.clothing);
  const circleColor = selectRandomKey(theme.colors.bgColors);
  const lipColor = selectRandomKey(theme.colors.lipColors);
  const hatColor = selectRandomKey(theme.colors.clothing);
  const faceMaskColor = selectRandomKey(theme.colors.clothing);

  const mask = true;
  const faceMask = false;
  const lashes = Math.random() > 0.5;

  return {
    skinTone,
    eyes,
    eyebrows,
    mouth,
    hair,
    facialHair,
    clothing,
    accessory,
    graphic,
    hat,
    body,
    hairColor,
    clothingColor,
    circleColor,
    lipColor,
    hatColor,
    faceMaskColor,
    mask,
    faceMask,
    lashes
  };
}

With it we can spread the props like this <BigHead {...getRandomOptions()} />.

image.png

4. DiceBear Avatars

If BigHeads wasn't enough then here comes the party crasher - DiceBear. This amazing library allows us to generate random avatars in 10 different styles: pixelated, cartoonish, initials only or even generative art like.

image.png

You may already recognize Avataaars which is another library on itself but is accessible through DiceBear random generation API.

Fortunately they also provide a URL:

export const generateDiceBearAvataaars = (seed) =>
  `https://avatars.dicebear.com/api/avataaars/${seed}.svg`;

image.png

The final code:

import { BigHead } from "@bigheads/core";

import {
  generateFakerAvatar,
  generateUnsplashImage,
  generateFakerAnimal,
  generateDiceBearGridy,
  generateDiceBearAvataaars,
  generateDiceBearBottts
} from "./utils";
import { getRandomOptions } from "./utils/bigheads";

export default function App() {
  const array = [0, 0, 0, 0, 0, 0];

  return (
    <div style={{ display: "flex", height: "100%" }}>
      {array.map((_, index) => (
        <div
          key={index}
          style={{ display: "flex", flexDirection: "column", gap: "20px" }}
        >
          <img src={generateFakerAvatar()} width="200" alt="faker_avatar" />
          {/* <img src={generateFakerAnimal()} width="200" alt="animal_avatar" />
          <img
            src={generateUnsplashImage()}
            width="200"
            alt="unsplash_avatar"
          /> */}
          <img
            src={generateDiceBearGridy(Math.random())}
            width="200"
            alt="bottts_avatar"
          />
          <img
            src={generateDiceBearBottts(Math.random())}
            width="200"
            alt="bottts_avatar"
          />
          <div style={{ width: "200px" }}>
            <BigHead {...getRandomOptions()} />
          </div>
          <img
            src={generateDiceBearAvataaars(Math.random())}
            width="200"
            alt="avataaars_avatar"
          />
          <img
            src={generateDiceBearBottts(Math.random())}
            width="200"
            alt="bottts_avatar"
          />
        </div>
      ))}
    </div>
  );
}

If you want to check out the code here is the CodeSandbox.

Check more of my work at alexstreza.dev.

I hope you enjoyed this short showcase of Avatar Generators and would love if you give this article a 🦄!

 
Share this