Universal avatar makes it possible to fetch/generate an avatar based on the information you have about that user.

Last update: Jun 17, 2022

<Avatar> Build Status npm downloads version npm bundle size (minified + gzip) npm type definitions

Universal avatar makes it possible to fetch/generate an avatar based on the information you have about that user. We use a fallback system that if for example an invalid Facebook ID is used it will try Google, and so on.

React Avatar component preview

For the moment we support following types:

The fallbacks are in the same order as the list above were Facebook has the highest priority.

Demo

Check it live!

Install

Install the component using NPM:

$ npm install react-avatar --save

# besides React, react-avatar also has prop-types as peer dependency,
# make sure to install it into your project
$ npm install prop-types --save

Or download as ZIP.

Note on usage in Gatsby projects

Users of Gatsby who are experiencing issues with the latest release should install [email protected] instead. This is an older version (v3.7.0) release of react-avatar that still used [email protected].

If you'd like to use the latest version of react-avatar have a look at #187 for a workaround and #187, #181 and #198 for a description of the issue.

Usage

  1. Import Custom Element:

    import Avatar from 'react-avatar';
  2. Start using it!

    <Avatar name="Foo Bar" />

Some examples:

<Avatar googleId="118096717852922241760" size="100" round={true} />
<Avatar facebookId="100008343750912" size="150" />
<Avatar githubHandle="sitebase" size={150} round="20px" />
<Avatar vkontakteId="1" size="150" />
<Avatar skypeId="sitebase" size="200" />
<Avatar twitterHandle="sitebase" size="40" />
<Avatar name="Wim Mostmans" size="150" />
<Avatar name="Wim Mostmans" size="150" textSizeRatio={1.75} />
<Avatar value="86%" size="40" />
<Avatar size="100" facebook-id="invalidfacebookusername" src="http://www.gravatar.com/avatar/a16a38cdfe8b2cbd38e8a56ab93238d3" />
<Avatar name="Wim Mostmans" unstyled={true} />

Manually generating a color:

import Avatar from 'react-avatar';

<Avatar color={Avatar.getRandomColor('sitebase', ['red', 'green', 'blue'])} name="Wim Mostmans" />

Configuring React Avatar globally

import Avatar, { ConfigProvider } from 'react-avatar';

<ConfigProvider colors={['red', 'green', 'blue']}>
    <YourApp>
        ...
        <Avatar name="Wim Mostmans" />
        ...
    </YourApp>
</ConfigProvider>

Options

Avatar

Attribute Options Default Description
className string Name of the CSS class you want to add to this component alongside the default sb-avatar.
email string String of the email address of the user.
md5Email string String of the MD5 hash of email address of the user.
facebookId string
twitterHandle string
instagramId string
googleId string
githubHandle string String of the user's GitHub handle.
skypeId string
name string Will be used to generate avatar based on the initials of the person
maxInitials number Set max nr of characters used for the initials. If maxInitials=2 and the name is Foo Bar Var the initials will be FB
initials string or function defaultInitials Set the initials to show or a function that derives them from the component props, the method should have the signature fn(name, props)
value string Show a value as avatar
alt string name or value The alt attribute used on the avatar img tag. If not set we will fallback to either name or value
title string name or value The title attribute used on the avatar img tag. If not set we will fallback to either name or value
color string random Used in combination with name and value. Give the background a fixed color with a hex like for example #FF0000
fgColor string #FFF Used in combination with name and value. Give the text a fixed color with a hex like for example #FF0000
size length 50px Size of the avatar
textSizeRatio number 3 For text based avatars the size of the text as a fragment of size (size / textSizeRatio)
textMarginRatio number .15 For text based avatars. The size of the minimum margin between the text and the avatar's edge, used to make sure the text will always fit inside the avatar. (calculated as size * textMarginRatio)
round bool or length false The amount of border-radius to apply to the avatar corners, true shows the avatar in a circle.
src string Fallback image to use
style object Style that will be applied on the root element
unstyled bool false Disable all styles
onClick function Mouse click event

ConfigProvider

Attribute Options Default Description
colors array(string) default colors A list of color values as strings from which the getRandomColor picks one at random.
cache cache internal cache Cache implementation used to track broken img URLs
initials function defaultInitials A function that derives the initials from the component props, the method should have the signature fn(name, props)
avatarRedirectUrl URL undefined Base URL to a Avatar Redirect instance

Example

import Avatar, { ConfigProvider } from 'react-avatar';

<ConfigProvider colors={['red', 'green', 'blue']}>
    <YourApp>
        ...
        <Avatar name="Wim Mostmans" />
        ...
    </YourApp>
</ConfigProvider>

Cache

This class represents the default implementation of the cache used by react-avatar.

Looking to implement more complex custom cache behaviour?

Attribute Options Default Description
cachePrefix string react-avatar/ The prefix for localStorage keys used by the cache.
sourceTTL number 604800000 (7 days) The amount of time a failed source is kept in cache. (in milliseconds)
sourceSize number 20 The maximum number of failed source entries to keep in cache at any time.

usage

import Avatar, { Cache, ConfigProvider } from 'react-avatar';

const cache = new Cache({

    // Keep cached source failures for up to 7 days
    sourceTTL: 7 * 24 * 3600 * 1000,

    // Keep a maximum of 20 entries in the source cache
    sourceSize: 20
});

// Apply cache globally
<ConfigProvider cache={cache}>
    <YourApp>
        ...
        <Avatar name="Wim Mostmans" />
        ...
    </YourApp>
</ConfigProvider>

// For specific instances
<Avatar name="Wim Mostmans" cache={cache} />

Avatar Redirect

Avatar Redirect adds support for social networks which require a server-side service to find the correct avatar URL.

Examples of this are:

  • Twitter
  • Instagram

An open Avatar Redirect endpoint is provided at https://avatar-redirect.appspot.com. However this endpoint is provided for free and as such an explicit opt-in is required as no guarantees can be made about uptime of this endpoint.

Avatar Redirect is enabled by setting the avatarRedirectUrl property on the ConfigProvider context

Development

In order to run it locally you'll need to fetch some dependencies and a basic server setup.

  • Install local dependencies:

    $ npm install
  • To test your react-avatar and your changes, start the development server and open http://localhost:8000/index.html.

    $ npm run dev
  • To create a local production build into the lib and es folders.

    $ npm run build

Implementing a custom cache

cache as provided to the ConfigProvider should be an object implementing the methods below. The default cache implementation can be found here

Method Description
set(key, value) Save value at key, such that it can be retrieved using get(key). Returns undefined
get(key) Retrieve the value stored at key, if the cache does not contain a value for key return null
sourceFailed(source) Mark the image URL specified in source as failed. Returns undefined
hasSourceFailedBefore(source) Returns true if the source has been tagged as failed using sourceFailed(source), otherwise false.

Reducing bundle size

Webpack 4

When using webpack 4 you can rely on tree shaking to drop unused sources when creating your Avatar component like the example below.

import { createAvatarComponent, TwitterSource } from 'react-avatar';

const Avatar = createAvatarComponent({
    sources: [ TwitterSource ]
});

Exported sources:

  • GravatarSource
  • FacebookSource
  • GithubSource
  • SkypeSource
  • ValueSource
  • SrcSource
  • IconSource
  • VKontakteSource
  • InstagramSource
  • TwitterSource
  • GoogleSource
  • RedirectSource

Without Webpack >= 4

If you are using a version of webpack that does not support tree shaking or are using a different bundler you'll need to import only those files you need.

ES6 modules

import createAvatarComponent from 'react-avatar/es/avatar';
import TwitterSource from 'react-avatar/es/sources/Twitter';

const Avatar = createAvatarComponent({
    sources: [ TwitterSource ]
});

Transpiled ES5 javascript / commonjs

const createAvatarComponent = require('react-avatar/lib/avatar').default;
const TwitterSource = require('react-avatar/lib/sources/Twitter').default;

const Avatar = createAvatarComponent({
    sources: [ TwitterSource ]
});

Products using React Avatar

Contributing

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -m 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

History

For detailed changelog, check Releases.

Maintainers

License

MIT License

GitHub

https://github.com/sitebase/react-avatar/
Comments
  • 1. React Avatar doesn't let me use `core-js 3.4.4`

    Hello :) I found this amazing library today by the way.

    I see in your package json you have corejs-2.5.7 . In our new project we are using latest Babel7 and corejs3.4.4 and we are getting the below errors :

    ERROR in ./node_modules/react-avatar/es/utils.js
    Module not found: Error: Can't resolve 'core-js/modules/es7.symbol.async-iterator' in 'C:\Atlassian\retailer_portal\node_modules\react-avatar\es'
     @ ./node_modules/react-avatar/es/utils.js 7:0-51
     @ ./node_modules/react-avatar/es/avatar.js
     @ ./node_modules/react-avatar/es/index.js
     @ ./src/client/components/AvatarControl/index.jsx
     @ ./src/client/components/index.js
     @ ./src/client/routes.jsx
     @ ./src/client/index.jsx
     @ multi webpack-dev-server/client?http://localhost:3000 webpack/hot/dev-server ./src/client/index.jsx
    
    ERROR in ./node_modules/react-avatar/es/utils.js
    Module not found: Error: Can't resolve 'core-js/modules/web.dom.iterable' in 'C:\Atlassian\retailer_portal\node_modules\react-avatar\es'
     @ ./node_modules/react-avatar/es/utils.js 9:0-42
     @ ./node_modules/react-avatar/es/avatar.js
     @ ./node_modules/react-avatar/es/index.js
     @ ./src/client/components/AvatarControl/index.jsx
     @ ./src/client/components/index.js
     @ ./src/client/routes.jsx
     @ ./src/client/index.jsx
     @ multi webpack-dev-server/client?http://localhost:3000 webpack/hot/dev-server ./src/client/index.jsx
    
    ERROR in ./node_modules/react-avatar/es/avatar.js
    Module not found: Error: Can't resolve 'core-js/modules/web.dom.iterable' in 'C:\Atlassian\retailer_portal\node_modules\react-avatar\es'
     @ ./node_modules/react-avatar/es/avatar.js 6:0-42
     @ ./node_modules/react-avatar/es/index.js
     @ ./src/client/components/AvatarControl/index.jsx
     @ ./src/client/components/index.js
     @ ./src/client/routes.jsx
     @ ./src/client/index.jsx
     @ multi webpack-dev-server/client?http://localhost:3000 webpack/hot/dev-server ./src/client/index.jsx
    
    ERROR in ./node_modules/react-avatar/es/context.js
    Module not found: Error: Can't resolve 'core-js/modules/web.dom.iterable' in 'C:\Atlassian\retailer_portal\node_modules\react-avatar\es'
     @ ./node_modules/react-avatar/es/context.js 5:0-42
     @ ./node_modules/react-avatar/es/avatar.js
     @ ./node_modules/react-avatar/es/index.js
     @ ./src/client/components/AvatarControl/index.jsx
     @ ./src/client/components/index.js
     @ ./src/client/routes.jsx
     @ ./src/client/index.jsx
     @ multi webpack-dev-server/client?http://localhost:3000 webpack/hot/dev-server ./src/client/index.jsx
    

    Can you please update corejs to version 3 or give us a workaround :) . Thank you @JorgenEvens

    Reviewed by goxr3plus at 2019-11-27 14:32
  • 2. Remove engines field from package.json

    The engines field is causing yarn to stumble. I'm running node 9 and I can't install react-avatar without the --ignore-engines flag. Considering the plugin is already compiled to es5 do you mind if we just remove it?

    [1/4] 🔍  Resolving packages...
    [2/4] 🚚  Fetching packages...
    error [email protected]: The engine "node" is incompatible with this module. Expected version "8.x.x".
    error Found incompatible module
    
    Reviewed by allanhortle at 2018-01-02 03:55
  • 3. Automatically adding star (*) sometimes on UI instead of image

    I have used this packages to load the images from local directory. but sometimes it renders the following html inside sb-avatar class which shows start symbol in the box.

    <div class="pull-left mt-1 sb-avatar__text" style="width: 100px;height: 100px;font-size: 33.3333px;line-height: 100px;text-align: center;text-transform: uppercase;color: rgb(255, 255, 255);background: rgb(103, 174, 63);">✷</div>

    Reviewed by AbhaysinghBhosale at 2019-02-27 11:40
  • 4. src property not working

    Image not showing here's my code: <Avatar src={localStorage.getItem('imgURL')} name={localStorage.getItem('companyName')} round/>

    Also tried to put string url on src but it same result

    Reviewed by EndStatement at 2018-10-05 14:58
  • 5. Unmount state fix

    I encountered issue when componentWillUnmount try to update active on undefined.

    So I made small change to componentWillUnmount to make state updates safer.

    A additional section in demo is added to demonstrate cached avatars as well.

    Reviewed by xiaotian-tan at 2018-07-19 06:36
  • 6. Any good alternative to this component?

    Since there's little or null (or maybe undefined, idk) interest from the repo's owner on maintaining this, it would be nice if we could share some alternatives here. Or maybe start making our own. Who's with me on this?

    Reviewed by javorosas at 2018-03-09 21:20
  • 7. Cannot resolve core-js

    Gatsby Error using npm

    Can't resolve 'core-js/modules/es.array.concat' in 'C:\Users\Donald Boulton\Documents\GitHub\publiuslogic\publiuslogic\node_modules\react-avatar\es\sources'

    Can't resolve 'core-js/modules/ANY AND ALL MODULES IN THIS DIRECTORY' in 'C:\Users\Donald Boulton\Documents\GitHub\publiuslogic\publiuslogic\node_modules\react-avatar\es\sources'

    File: node_modules\react-avatar\es\sources\Github.js

    package-json-lock ile is calling two versions of core.js ??? "react-avatar": { "version": "3.9.0", "resolved": "https://registry.npmjs.org/react-avatar/-/react-avatar-3.9.0.tgz", "integrity": "sha512-i9UR3z/Y4JhAb6WH0yaAr6noLwLVgUyp7kOMu48Plc9ch6OQ3k4aDqp+m0TrCbHAn8YfRv2BevK9gA0nIqwVbA==", "requires": { "core-js": "^3.6.1", "is-retina": "^1.0.3", "md5": "^2.0.0" }, "dependencies": { "core-js": { "version": "3.6.4", "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.6.4.tgz", "integrity": "sha512-4paDGScNgZP2IXXilaffL9X7968RuvwlkK3xWtZRVqgd8SYNiVKRJvkFd1aqqEuPfN7E68ZHEp9hDj6lHj4Hyw==" } }

    Reviewed by donaldboulton at 2020-01-27 15:43
  • 8. Migrate to prop-types module.

    From React v15.5.0: Accessing PropTypes via the main React package is deprecated. React.PropTypes is replaced with PropTypes from 'prop-types' module. This fixes #59

    Reviewed by anlesk at 2017-05-23 15:34
  • 9. Showing '*' randomly when 'name' and 'src' are set

    Hello, First of all, great plugin. Now to the point. I saw a similar closed issue where it was an async issue due to the way setState method works. But i'm getting this error when the src url could not be loaded.

    Reviewed by gauravshah137 at 2017-03-21 07:28
  • 10. Any thoughts on cache expiration?

    I realized that it's possible to create a custom cache module, but I wonder if there's any thought of developing a cache module that intelligently expires the "bad links"? Specifically, the current use of localStorage maintains the "bad link" list forever (until the user explicitly clears the cache). Since users will often add and update their external avatar images, it would be better to put a time limit on the cache.

    Reviewed by Eric24 at 2019-03-08 04:40
  • 11. Updated to latest version with Initial changes and Initials are broken

    screen shot 2018-09-14 at 11 22 16

    My avatar component looks like:

    <Avatar className="d-none d-md-block" color="#1CA3AE" fgColor="#ffffff" name={`${firstName} ${lastName}`} round={true} size="39" />

    Reviewed by seandelaney at 2018-09-14 10:25
  • 12. text in name can be selected

    The text in atribute name. are can be selected. Yeah, I can "fix" it with user-select:none, But I think it looks cool when it can't be selected by default.

    Btw homepage in npmjs.com opens the page with 404 error

    Reviewed by ksixen at 2022-01-28 13:11
  • 13. Not working in ReactDomServer

    Hi. I'm trying to generate avatar in "ReactDOMServer.renderToStaticNodeStream" but it's not working. In output everything looks correct apart content in span tag. It's empty. It doesn't matter if I'm trying to generate avatar as a picture or initials, always output is incorrect.

    
    <div class="attorney-avatar-nav-bar sb-avatar" style="display: inline-block; vertical-align: middle; width: 16px; height: 16px; border-radius: 100%; font-family: Helvetica, Arial, sans-serif;">
        <div class="attorney-avatar-nav-bar sb-avatar__text" style="width: 16px; height: 16px; line-height: initial; text-align: center; color: #fff; border-radius: 100%;" title="Mitchell Griffith">
            <div style="display: table; table-layout: fixed; width: 100%; height: 100%;">
                <span style="display: table-cell; vertical-align: middle; font-size: 100%; white-space: nowrap;">
                	<span></span>
                </span>
            </div>
        </div>
    </div>
    

    What is wrong? Thank you.

    Reviewed by kapdom at 2020-10-15 06:59
  • 14. UseEffect not rerendered

    Hi, if I extract the react-avatar to an apart component it rendered only once, and not changed on a useEffect state. What this can be? I suspect that it is cached, but a cache not enabled on the react-avatar

    Reviewed by andrconstruction at 2020-10-14 18:42
  • 15. add HTML data attribute to avatar wrapper

    Hello. I wanna add HTML data attribute to the avatar wrapper that has sb-avatar class. How could I do this? Is there any way to pass data attribute to Avatar component?

    Reviewed by theMasix at 2020-09-16 04:48
  • 16. Feature Request: Support Cloudinary CDN

    Hello. I use this package for my entire avatar serving in React. Today, I got acquainted with Cloudinary CDN. I wonder if we could have cloudinray-specific support: Give the image name and image config to the package, then the package make the correct image url and serve it. I think it would be useful. I know the Cloudinary has its own React SDK. So what we might do is only merge the SDK with this package.

    Reviewed by theMasix at 2020-06-21 13:02
An npm package that lets you jump right into coding React and Redux with universal (isomorphic) rendering. Only manage Express setups or Webpack configurations if you want to.

Universal Redux What and Why Universal Redux is an npm package that when used as a dependency in your project provides a universal (isomorphic) render

May 22, 2022
💅 Micro-library to write stylesheets with a non-opinionated approach, free of dependencies, and in the easiest way possible.
💅 Micro-library to write stylesheets with a non-opinionated approach, free of dependencies, and in the easiest way possible.

react-native-styl is a micro-library for React Native developers whose goal is to write stylesheets with a non-opinionated library, free of dependenci

Jun 10, 2022
A boilerplate template for making your awesome dApp on IoTeX and ETH, BSC, and other possible chains
A boilerplate template for making your awesome dApp on IoTeX and ETH, BSC, and other possible chains

Bounties ?? Please notice: If you have your own custom project and you want to r

May 13, 2022
CLI based on Vite to generate your project easily
CLI based on Vite to generate your project easily

CLI based on Vite to generate your project easily

Jun 13, 2022
Boilerplate for react universal (isomorphic) application based on flux architecture (redux implementation)
Boilerplate for react universal (isomorphic) application based on flux architecture (redux implementation)

Redux universal boilerplate Boilerplate for react universal application building on flux architecture based on redux implementation. Boilerplate based

Mar 30, 2022
Storybook-addon-next - A no config Storybook addon that makes Next.js features just work in Storybook

Storybook Addon Next ?? No config support for Next.js: Tired of writing and debu

Jun 24, 2022
Fluent Blocks makes it easy to use Fluent & UI Kit designs in app development.

Fluent Blocks makes it easy to use Fluent & UI Kit designs in app development. This repository provides a set of packages developers can use to build

May 11, 2022
CLI tool that makes react boilerplate component. Supports es6 or typescript, css or @emotion/styled, emmet-like syntax.
CLI tool that makes react boilerplate component. Supports es6 or typescript, css or @emotion/styled, emmet-like syntax.

CLI tool that makes react boilerplate component. Supports es6 or typescript, css or @emotion/styled, emmet-like syntax.

May 24, 2022
A front end project using react js, html and CSS to fetch data from the pokemon API.

A front end project using react js, html and CSS to fetch data from the pokemon API. The web application searches for Pokemon characters and displays their stats and images.

Nov 1, 2021
A React hook to fetch ENS records from a domain.

use-ens A React hook to fetch ENS records from a domain. Install pnpm i use-ens Example import React, { useEffect } from 'react' import { useWeb3React

Mar 15, 2022
A CLI and toolbox to extract information from React component files for documentation generation purposes.

react-docgen react-docgen is a CLI and toolbox to help extracting information from React components, and generate documentation from it. It uses ast-t

Jun 24, 2022
I have Created Static Gaming Website ui. Tech stack used in this web : - React, Tailwind,
I have Created Static Gaming Website ui. Tech stack used in this web : - React, Tailwind,

I have Created This Beautiful UI Using React.js & Tailwind I'm not much good in ui designing that's why i'm doing practice if you want me recommend me

Jun 12, 2022
I have created a real time currency converter using api in react
I have created a real time currency converter using api in react

React Currency Converter Review ↓ Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the

May 20, 2022
I have created a Login page type of app using react.js

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Dec 28, 2021
Tutorial from the channel I want to be a dev for beginners on the front-end. Here we have the initial steps for testing in react.

Tutorial from the channel I want to be a dev for beginners on the front-end. Here we have the initial steps for testing in react.

Jun 1, 2022
A cli tool to generate cra-template from current create-react-app project.

Create Cra Template A cli tool to generate cra-template from current create-react-app project. Create Cra Template Templates cra-template-popular cra-

Jun 1, 2022
🔑 Generate good customizable passwords
🔑 Generate good customizable passwords

Welcome to password-generator-web ?? ?? password-generator-web in production... ?? Generate good customizable passwords Screenshots ?? Table Of Conten

Jan 28, 2022
generate forms from JSON object
generate forms from JSON object

json-obj-form-generator generate forms from JSON object Install npm install --save json-obj-form-generator For more informations check documentation w

Nov 10, 2021
Fluid-type-scale-calculator - Generate font size variables for a fluid type scale with CSS clamp
Fluid-type-scale-calculator - Generate font size variables for a fluid type scale with CSS clamp

Fluid Type Scale Calculator Generate font size variables for a fluid type scale

Jun 18, 2022