Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

How to Create an Avatar in React Using MUI Avatar

An MUI Avatar is a graphical representation of a user’s identity within a web application, often displayed in the form of a profile picture, initials, or an icon. MUI, a popular React UI framework, provides the Avatar component as part of its library, allowing developers to easily integrate and customize avatars in their applications.

Avatars serve to enhance the visual appeal of user interfaces, contributing to a more engaging and personalized user experience by visually representing individuals or entities. MUI avatars can be utilized to display profile pictures, generate letter avatars dynamically, or even include icons, offering a versatile solution for user representation in React applications.

PS: Engineers waste time building and styling components when working on a project, writing repetitive markup adds time to the project and is a mundane, boring task for engineers. PureCode.ai uses AI to generate a large selection of custom, styled UI components for different projects and component types.

Importance of Avatars in Web Applications

Before we dive deeper into MUI Avatars, let us first take a look at the importance of Avatars in our applications and why we would need them in our applications.

Avatars play a significant role in web applications, offering various benefits that enhance user experience, engagement, and visual appeal. Here are some of the key importance of avatars in web applications:

Importance Table:

FeaturesImportance
User IdentificationAvatars serve as visual identifiers, helping users quickly recognize and associate content with specific individuals. This is especially valuable in social media platforms, forums, and collaborative environments.
PersonalizationProviding users with the ability to set or customize their avatars adds a personal touch to their profiles. This personalization enhances the overall user experience and encourages a sense of ownership and identity.
Visual Appeal and BrandingAvatars contribute to the visual appeal of a web application. Well-designed avatars can add a touch of creativity, color, and personality, contributing to the overall aesthetic and branding of the platform.
Enhanced EngagementIn scenarios like comment sections, discussion forums, or messaging apps, avatars make interactions more engaging. Users are more likely to engage in conversations when they can associate messages with distinct avatars.
Recognition and MemorabilityAvatars help users remember other users, making it easier to recognize familiar individuals across different sections of the application. This recognition is especially important in collaborative and community-driven platforms.
Feedback and NotificationsAvatars can be used to represent users in notifications and feedback messages. For example, when someone likes a post or sends a message, their avatar can be included in the notification, providing visual feedback about the action.
Gamification and Progress IndicatorsIn gamified applications or systems with user achievements, avatars can be used to visually represent progress, levels, or achievements. This adds a gamification element to the user experience.
Accessibility and InclusivityAvatars can be designed to accommodate accessibility features, such as alternative text and high-contrast colors. This ensures that users with disabilities can still benefit from visual identification.
Reduced Anonymity and Improved Community BuildingIn online communities, avatars reduce the sense of anonymity by associating content with specific individuals. This can lead to a more positive and accountable community environment.
Differentiation in Data RepresentationIn applications where data is presented in a tabular or list format, avatars can differentiate entries, making it easier for users to distinguish between items and quickly identify relevant information.

Creating Image Avatars with the MUI Avatar Component

Here, we’ll be discussing how to create image avatars using Material UI’s avatar component such that one can associate user profile pictures with their accounts. MUI helps simplify this process in one of two ways, and here’s how:

  1. Using the `src` prop to link the avatar to the user’s image:Add an `alt` attribute for accessibility and graceful fallbacks then customize the size and shape of the avatar if needed.

    import Avatar from '@material-ui/core/Avatar'; const CustomAvatar = () => {   return (     <Avatar alt="John Doe" src="/path-to-image.jpg" />   ); }

    In the above example, the React component CustomAvatar uses Material UI’s Avatar component to display a custom image avatar. It sets the alternative text (alt) to “John Doe” and the image source (src) to “/path-to-image.jpg”. See the output below:

    Image avatars with src prop
  2. Passing a `backgroundImage` value to the `sx` prop:

    import Avatar from '@mui/joy/Avatar';
    
    const ImageAvatar = ({ backgroundImage }) => {
      return (
        <Avatar
          sx={{
            width: 100,
            height: 100,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            backgroundImage: `url(${backgroundImage})`,
          }}
        />
      );
    }
    
    const CustomAvatar = () => {
      const backgroundImageUrl = 'your-image-url.jpg'; // Replace with the URL of your image
    
      return (
        <div>
          <ImageAvatar backgroundImage={backgroundImageUrl} />
        </div>
      );
    }

    In the code above, we define a CustomAvatar component that uses Material-UI’s Avatar. It includes a customizable ImageAvatar component, allowing us to display an avatar with a specified background image URL. Also, the styles are set using the ‘sx’ prop to achieve a specific appearance for the avatar. See the output of the above example:

    Image avatars with the sx prop

Creating Letter Avatars with the MUI Avatar Component

Now that we’ve learned how to create avatars using images, let us dive into how to create avatars using letters.

In cases where user profile images are unavailable, you can generate letter avatars dynamically using MUI props. Here’s how to do it:

  1. Instead of the `src` attribute, provide the `children` attribute with the user’s initials.
  2. Customize the background color, text color, and size.
  3. Ensure that the text initials display clearly.

The code below creates a custom avatar. The avatar has a purple background and white text, and displays the initials “JD.” The styles are applied directly here using the style prop within the JSX.

import Avatar from '@material-ui/core/Avatar';

const customAvatar = () => {
  return (
    <Avatar style={{ background: 'purple', color: 'white' }}>JD</Avatar>
  );
}

Here’s the output of the above example:

Letter avatars with mui avatar component

Customizing Material UI Avatar Sizes and Colors

In this section, we’ll be discussing how to customize MUI Avatar sizes and colors.

MUI allows for extensive customization of avatar sizes and colors. You can adapt avatars to your application’s design using the following:

  1. Modify the `style` attribute to control the size, shape, and color of avatars.

  2. Adjust the background color, text color, and font size for letters.

  3. Experiment with different color schemes to match your app’s aesthetics.

In the code below, we created a custom avatar using MUI’s Avatar component. We gave the avatar a blue background, white text, a width and height of 48 pixels each, and a font size of 24 pixels. The styles are applied directly using the style prop within the JSX.

import Avatar from '@material-ui/core/Avatar';

const CustomAvatar = () => {
  return (
    <Avatar
      style={{
        backgroundColor: 'blue',
        color: 'white',
        width: '48px',
        height: '48px',
        fontSize: '24px',
      }}
    >
      JD
    </Avatar>
  );
}

Here’s the output of the above example:

Sizes and colors with MUI avatar component

Creating Icon Avatars with the Material UI Avatar Component

In this section, we’ll be learning how icons also function as avatars to represent specific user roles or attributes and this section will help us understand how it is done.

MUI helps simplify the process to create icon avatars by doing the following:

  1. Use MUI’s Icon component for your avatar.

  2. Select an appropriate icon from the Material Icons library.

  3. Customize the icon’s size, color, and background as needed.

In this example, we created a custom avatar that has a green background, and white text, and displays an icon represented by the <Icon> component with the “face” icon name, and the styles are also applied directly using the style prop within the JSX.

import Avatar from '@material-ui/core/Avatar';
import Icon from '@material-ui/core/Icon';

const CustomAvatar = () => {

  return (

    <Avatar style={{ background: 'green', color: 'white' }}>

      <Icon>face</Icon>

    </Avatar>

  );

}

Material UI Avatar Variants

In this section, we’ll be delving into the different avatar variants that MUI offers, such as circular avatars and square avatars. These variants are different based on your design preferences.

In the below code, the CustomAvatar displays three avatars in a horizontal row. Each of these avatars represents different users (User 1, User 2, and User 3) and the images for each user are imported from local files (user1.jpg, user2.jpg, and user3.jpg). Finally, we arrange the avatars in a flex container with a gap of 8 pixels between them.

import Avatar from '@material-ui/core/Avatar';
import user1 from './user1.jpg';
import user2 from './user2.jpg';
import user3 from './user3.jpg';

const CustomAvatar = () => {
  return (
    <div style={{ display: 'flex', gap: '8px' }}>
      <Avatar alt="User 1" src={user1}/>
      <Avatar alt="User 2" src={user2} />
      <Avatar alt="User 3" src={user3}/>
    </div>
  );
}

Here’s what the output will look like:

MUI avatar variants

Handling Avatar Fallbacks in MUI

How do we handle Avatar fallbacks in MUI? This is crucial to ensure a seamless user experience, especially when user-specific images are unavailable. Fallback mechanisms come into play when, for instance, a user hasn’t uploaded a profile picture or when there are connectivity issues retrieving the image.

In MUI, you can address this by using the onError prop provided by the Avatar component. This prop allows you to define a callback function that executes when the avatar image encounters an error.

Here’s an example of how you can handle avatar fallbacks in Material-UI:

import React, { useState } from 'react';
import Avatar from '@mui/joy/Avatar';

const CustomAvatar = () => {
  const [imageError, setImageError] = useState(false);

  const handleImageError = () => {
    setImageError(true);
  };

  return (
    <Avatar
      alt="User"
      src={imageError ? null : '/user.jpg'} 
      onError={handleImageError} 
    />
  );
};

In this example, The CustomAvatar component uses the Avatar component from Material-UI. It maintains a state variable imageError using the useState hook to track whether an image error occurs. Then, the handleImageError function sets the imageError state to true during an image error. We set the onError prop of the Avatar component to the handleImageError function. If the avatar image fails to load, this function is called and the src prop of the Avatar component is conditionally set based on the imageError state. If there is an error, we set to a fallback image or null.

This approach ensures graceful handling of avatar image errors and provides a way to display fallback content or a default avatar in case of loading issues.

Creating Grouped Avatars Using MUI

In this section, we’ll be looking at two methods of creating grouped avatars with Material UI. They are;

  • Total Avatars: These avatars could represent users, contributors, or any entities that require visual identification.

  • Custom Surplus Avatars: Use these avatars when you have more avatars to display than can fit in a group or screen.

Let’s delve deeper into them and build avatars with them.

Total Avatars

This avatar group refers to a use case where you dynamically generate avatars for a predefined number of users within your application. This functionality is often employed in scenarios like user directories, team collaboration tools, or any context where a visual representation of a specific number of users is essential.

Here’s an instance with code:

import Avatar from '@material-ui/core/Avatar';

const CustomAvatar = ({ totalUsers }) => {
  return (
    <div style={{ display: 'flex', gap: '8px' }}>
      {Array.from({ length: totalUsers }, (_, index) => (
        <Avatar key={index} alt={`User ${index + 1}`} src={`/user${index + 1}.jpg`} />
      ))}
    </div>
  );
}

In the above code, the TotalAvatars component takes a prop `totalUsers` to determine the number of avatars to generate. It utilizes the `Array.from` method to create an array with a length equal to totalUsers, and for each element, it generates an Avatar component with a unique key, alt text, and source.

Custom Surplus Avatars

This avatar group addresses the situation where the number of avatars to be displayed exceeds the available space or a predefined limit. This feature ensures a visually pleasing user interface by intelligently handling and summarizing additional avatars that cannot be accommodated within the specified area.

Here’s a code example:

import Avatar from '@material-ui/core/Avatar';

const customAvatar = ({ avatars }) => {
  const maxAvatarsToShow = 3; // Set your desired maximum avatars to display

  const visibleAvatars = avatars.slice(0, maxAvatarsToShow);
  const surplusAvatars = avatars.slice(maxAvatarsToShow);

  return (
    <div style={{ display: 'flex', gap: '8px' }}>
      {visibleAvatars.map((avatar, index) => (
        <Avatar key={index} alt={`User ${index + 1}`} src={avatar} />
      ))}
      {surplusAvatars.length > 0 && (
        <Avatar alt={`+${surplusAvatars.length}`} style={{ backgroundColor: 'gray', color: 'white' }}>
          +{surplusAvatars.length}
        </Avatar>
      )}
    </div>
  );
}

In the above example, the AvatarGroup component takes an array of avatars as a prop. It calculates the number of visible avatars (maxAvatarsToShow) and the surplus avatars. It then maps through the visible avatars, creating an Avatar for each. If there are surplus avatars, it displays a summary avatar with a count, indicating the number of additional avatars not shown.

Building an Interactive Avatar with MUI

Here, I’ll be showing you how to build an interactive avatar with MUI. You can add various interactive features such as hover effects, clickable actions, or other dynamic behaviors.

Below is a simple example demonstrating how to create an interactive avatar with a hover effect using MUI:

import React, { useState } from 'react';
import Avatar from '@mui/joy/Avatar';

const CustomAvatar = () => {
  const [isHovered, setIsHovered] = useState(false);

  const handleMouseEnter = () => {
    setIsHovered(true);
  };

  const handleMouseLeave = () => {
    setIsHovered(false);
  };

  return (
    <Avatar
      alt="User"
      src="/user.jpg"
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      style={{
        transform: isHovered ? 'scale(1.8)' : 'scale(1)',
        transition: 'transform 0.3s ease-in-out',
        cursor: 'pointer',
      }}
    />
  );
};

In the above example, the CustomAvatar component uses the Avatar component from MUI and it uses the useState hook to manage the isHovered state, which tracks whether the avatar is currently being hovered. Two functions, handleMouseEnter and handleMouseLeave, update the isHovered state based on mouse enter and leave events.

The style prop of the Avatar component dynamically adjusts based on the isHovered state. It scales the avatar up by 20% on hover using the transform property and includes a smooth transition effect and the cursor property is set to ‘pointer’ to indicate that the avatar is clickable.

Here’s how it looks before hover:

And on hover, it looks like this:

Building an Avatar with a Badge

Adding a badge to an avatar allows you to display supplementary information, such as online status, notifications, or user roles. MUI provides components that make it straightforward to create avatars with badges.

In the below code, we utilize the MUI’s Badge component to create a custom avatar. The avatar, sourced from “/user.jpg,” has a circular badge in the bottom-right corner. The badge contains a mail icon (MailIcon) with a font size of 16 pixels, serving as an indicator for new messages or notifications.

import Avatar from '@mui/joy/Avatar';
import Badge from '@mui/joy/Badge';
import MailIcon from '@mui/icons-material/Mail';

const customAvatar = () => {
  return (
    <Badge
      overlap="circular"
      anchorOrigin={{
        vertical: 'bottom',
        horizontal: 'right',
      }}
      badgeContent={<MailIcon style={{ fontSize: 16 }} />}
    >
      <Avatar alt="User" src="/user.jpg" />
    </Badge>
  );
};

And here’s how it’ll look

An avatar with a badge

Best Practices

When implementing MUI avatars, prioritize accessibility to ensure a seamless user experience for all individuals, including those with disabilities. Adhere to the following practices:

  • Alt Text: Provide meaningful alternative text `alt` for avatars, describing the content or purpose. Alt text is essential for screen readers and assists users who may not be able to view the visual content.

  • Contrast and Color Choices: Ensure sufficient contrast between the avatar and its background for users with visual impairments. Consider color choices that accommodate users with color blindness, using distinct colors or patterns for differentiation.

  • Keyboard Navigation: Make avatars accessible via keyboard navigation. Users should be able to focus on avatars and trigger actions using keyboard inputs, promoting an inclusive experience for those who rely on keyboard navigation.

Responsive designs and scalability

Create avatars with responsive designs to ensure optimal display across various devices and screen sizes. Consider the following practices:

  • Flexible Sizing: Use responsive sizing techniques to adapt avatars based on the screen size. This ensures a consistent and visually appealing representation on both large desktop screens and smaller mobile devices.

  • Media Queries: Employ CSS media queries to adjust avatar sizes, styles, or visibility based on the device’s characteristics. This helps in crafting a responsive layout that caters to the diverse range of devices users might utilize.

  • Progressive Loading: Implement techniques such as lazy loading for avatars, especially when dealing with a large number of users. Prioritize the loading of avatars within the user’s viewport, enhancing the performance of your web application.

Performance optimization of Avatars

Optimize the performance of avatars to maintain a smooth and efficient user experience. Consider the following strategies:

  • Image Compression: Compress an avatar image to reduce file sizes without compromising quality. This accelerates image loading times, particularly beneficial for users with slower internet connections.

  • Caching: Implement caching mechanisms to store avatars locally, reducing the need for repeated downloads. Utilize browser caching strategies or implement a caching layer on the server side.

  • CDN Integration: Consider leveraging Content Delivery Networks (CDNs) for serving avatar images. CDNs distribute content across multiple servers globally, minimizing latency and ensuring faster loading times for users irrespective of their geographical location.

By integrating these best practices, not only can one enhance the accessibility and inclusivity of MUI avatars but also ensure responsiveness and optimal performance, resulting in a more robust and user-friendly web application.

Examples and use cases

Here are some examples of MUI avatars in different scenarios:

User Profile Avatar

Displaying the profile picture of a user in a social media app, online community, or user account section.

import Avatar from '@mui/joy/Avatar';

const UserProfile = ({ user }) => {
  return (
    <Avatar alt={user.name} src={user.profilePicture} />
  );
};

Comment Section Avatar

Showing avatars next to user comments in a blog or discussion forum.

import React from 'react';
import Avatar from '@mui/material/Avatar';

const Comment = ({ commenter }) => {
  return (
    <div>
      <Avatar alt={commenter.name} src={commenter.profilePicture} />
      <span>{commenter.name}</span>
      <p>{commenter.commentText}</p>
    </div>
  );
};

Contact List Avatars

Creating a list of contacts with their avatars in a messaging app or contact management system.

import React from 'react';
import Avatar from '@mui/material/Avatar';

const ContactList = ({ contacts }) => {
  return (
    <ul>
      {contacts.map((contact) => (
        <li key={contact.id}>
          <Avatar alt={contact.name} src={contact.profilePicture} />
          {contact.name}
        </li>
      ))}
    </ul>
  );
};

Product Image Avatars

Representing product images in an e-commerce application.

import React from 'react';
import Avatar from '@mui/material/Avatar';

const ProductCard = ({ product }) => {
  return (
    <div>
      <Avatar alt={product.name} src={product.image} />
      <h3>{product.name}</h3>
      <p>{product.description}</p>
    </div>
  );
};

Notification Avatars

Displaying avatars in a notification panel to represent the sender of a notification.

import React from 'react';
import Avatar from '@mui/material/Avatar';

const Notification = ({ notification }) => {
  return (
    <div>
      <Avatar alt={notification.senderName} src={notification.senderAvatar} />
      <p>{notification.message}</p>
    </div>
  );
};

These examples showcase the versatility of MUI avatars in various contexts across different use cases, from user profiles to comment sections and beyond.

Final Thoughts on Material UI Avatar

According to the article, MUI avatars allow React developers to create user interfaces that are engaging and personalized and also offer a comprehensive toolkit for avatar customization, including rendering profile pictures, generating dynamic letter avatars, incorporating interactive elements and badges, and more. By following best practices in accessibility, responsiveness, and performance optimization, developers can successfully integrate avatars into various web applications.

MUI avatars not only enhance visual aesthetics but also play a crucial role in promoting user recognition and interaction. With their versatility and ease of implementation, MUI avatars are an invaluable asset for building immersive and user-centric React applications.

For your reference, you can also check out the below YouTube video to learn more about MUI avatar:

PureCode.ai can cater to your code development process. It will save you valuable time and effort on a project by providing customized, and ready-to-use components which will allow you to prioritize more important and thought-intensive tasks to speed up the development of your user interface.

Andrea Chen

Andrea Chen