Skip to content

RESOURCES / BLOG

Build an Avatar Image Generator

A user’s avatar represents their identity and is one of the most frequently used UI elements. Despite it being a small-sized object, it has enormous power when used in websites and other web applications. Web applications like this that allow personalization enhance the user’s experience and establish a bond between a product and its users.

This article demonstrates how to use Cloudinary to create a Next.js avatar image generator app. Next.js is a React-based framework with functionalities like pre-rendering, both static generation (SSG) and server-side rendering (SSR), automatic code-splitting for faster page loads, and API routes to build API endpoints with serverless functions for back-end features.

Web developers utilize the cloud-based media management tools within Cloudinary to manage media-related assets in web applications. In this tutorial, Cloudinary will be used to store, retrieve, and make numerous image alterations.

Moreover, with the increasing demand for personalization, there are several other features that can be integrated into avatar generators. These include:

Multiple Font Styles and Colors: Allowing users to choose from a variety of font styles and colors can make the avatar more personalized and in line with the user’s preferences.

Random Color Generation: Instead of sticking to a few predefined colors, providing an option to generate random colors can add an element of surprise and uniqueness to each avatar.

Use of Emojis: Emojis are universally recognized and loved. Incorporating them into the avatar can make it more fun and relatable.

Background Image Customization: Users can be given the option to choose a background image or an overlay, adding depth and character to the avatar.

No Registration Requirement: Making the avatar generator accessible without the need for registration can increase its usability and appeal to a wider audience.

You can fork this Codesandbox run the demo or get started quickly.

To follow the steps in this article, you must have:

- Adequate knowledge of JavaScript and React.js
- The latest version of Node.js installed
- A terminal such as ITerm2(Mac OS) or Git bash (Windows)
- A Cloudinary account - Create one [here](https://cloudinary.com/homepage-2).

After successfully creating an account, Cloudinary will us redirect to our account’s dashboard page, where we can see account details that will be useful later on, including:

- Cloud name
- API Key
- API Secret

NOTE: Do not share these details with anyone.

We create a Next.js app in a new folder called avatar-gen and run the following command in its terminal:

    npx create-next-app avatar-gen
    cd avatar-gen
    #install cloudinary for React SDK and Lodash
    npm install cloudinary-react lodash
Code language: CSS (css)

The code above snippet will install node packages for Next.js, Cloudinary React SDK, and lodash. Running npm run dev should render an app with an affirmative message on your browser:

In development, replace the default code in index.js with this:

    import Head from 'next/head'
    import styles from '../styles/Home.module.css';
    import React, { useState } from "react";
    
    export default function Home() {
     return (
     <div className={styles.container}>
           <h1 className={styles.title}>
              Avatar Generator
            </h1>
        </div>
      )
    }
Code language: JavaScript (javascript)

Next, in index.js let’s create a form with two input fields for a user’s First and Last name and assign them to a state variable called formData.

     const [formData, setFormData] = useState({
          firstName: '',
          lastName: ''
        })
Code language: JavaScript (javascript)

For the functionality of the input fields, we will declare a new function called handleChange for the onChange event handler, which detects when the value of an input field changes. The function stores the input’s current value in a state variable.

    const handleSubmit = (e) => {
    e.preventDefault();
        setFormData({
          firstName : '',
          lastName: ''
        })
      }
    }
    
    const handleChange = (e) =>{
        setFormData( {...formData, [e.target.name] : e.target.value})
      }
Code language: JavaScript (javascript)

In the code block above, we assigned a function — handleSubmit to the button’s onClick handler. The function handles the data that was entered into the form by the user.

We will define two state variables to store the values whenever the form is submitted and retrieve each value’s initial from both input fields.

    export default function Home() {
    const [pushedData, setPushedData] = useState()
    const [avatarInitials, setAvatarInitials] = useState({
        firstInitial: '',
        secondInitial: ''
      }) 
Code language: JavaScript (javascript)

We need to add a function that updates the state variables with the values after submitting the form. As a result, we will create a function that retrieves the values’ initials and reset the form.

    const handleSubmit = (e) => {
        e.preventDefault();
        getInitials(formData)
        setPushedData(formData)
        setFormData({
          firstName : '',
          lastName: ''
        })
      }
    
    const getInitials = (e) => {
        let firstName = e.firstName.split('');
        let lastName = e.lastName.split('');
        setAvatarInitials({
          firstInitial: firstName[0],
          secondInitial: lastName[0]
        })
        setText(true)
      }
Code language: JavaScript (javascript)

To access Cloudinary’s SDK(Software Development Kit), we import the required elements of the cloudinary-react library in the index.js file.

<!— Is this import suppose to be for index.js … perhaps using a comment like this one above code to specify to reader ’// index.js ’ —>

import {Image, Transformation, CloudinaryContext} from 'cloudinary-react';
Code language: JavaScript (javascript)

Then, in the CloudinaryContext component, we apply the Cloud name from our account details on the dashboard page and also include the publicId of the avatar image in the Image component:

<!— Can you please mention to place code within return() —>

export default function Home() {
  // component definitions

  return (
    <div className={styles.container}>
      {/* Head component */}

      <main className={styles.main}>
        <form className={styles.form}>
          <h1 className={styles.title}>Avatar Generator</h1>
          <div className={styles.image}>
            <CloudinaryContext cloudName="your-public-id">
              <Image publicId="sample" alt="profile">
                
              </Image>
            </CloudinaryContext>
          </div>
        </form>
      </main>
    </div>
  );
}
Code language: JavaScript (javascript)

You can use the publicId of any image in your Cloudinary account.

Next, we will use the Transformation component to convert the image to a blurry circular 150×150 thumbnail with “AB” as its default value.

    <CloudinaryContext cloudName="your-cloud-name">
      <Image publicId="sample" alt="profile">
        <Transformation width="150" height="150" gravity="face" effect="blur:200" radius="max" crop="thumb" />
        <Transformation background="#C5E5FC" />
        <Transformation overlay={{fontFamily: "Arial", fontSize: 50, fontWeight: "bold", text: "AB"}} color="white" />
      </Image>
    </CloudinaryContext>
Code language: HTML, XML (xml)

Finally, we create a boolean state variable to display the avatar’s initials and set it to false.

    const [text, setText] = useState(false)
Code language: JavaScript (javascript)

Then, use a ternary conditional rendering to replace the default value with data from avatarInitials if text is true; else, it should return “AB” as the default value.

    <CloudinaryContext cloudName="your-cloud-name">
      <Image publicId="sample" alt="profile">
        <Transformation width="150" height="150" gravity="face" effect="blur:200" radius="max" crop="thumb" />
        <Transformation background="#C5E5FC" />
        <Transformation overlay={{fontFamily: "Arial", fontSize: 50, fontWeight: "bold", text: `${text ? avatarInitials.firstInitial : "A"}${text ? avatarInitials.secondInitial : "B"}`}} color="white" />
      </Image>
    </CloudinaryContext>                    
Code language: HTML, XML (xml)

Here’s what the page looks like.

You can right-click on the avatar image and save it if you like.

<!— Ran into ERROR: loads/assign , solution: [yarn add lodash] —>

<!— Ran into ERROR: useState is not defined , solution [import React, { useState } from ‘react’; ] in index.js COMMENT-WILLIAM: Fixed all these thanks. —>

In this post we built an avatar image generator that takes in two names and makes an avatar image out of it. Try to change the background image of the generated avatar image to one in your Cloudinary account.

Here’s a link to the project repository on Github.

Start Using Cloudinary

Sign up for our free plan and start creating stunning visual experiences in minutes.

Sign Up for Free