material-ui > Avatar
Material-UI Avatar Examples with Styled-components
In the following examples you will see how to use Material-UI's Avatar component, along with its close friend AvatarGroup.
Why styled-components? Well, Material-UI happens to be converting everything to a styled-components approach.
This means that soon,
makeStyles will be a thing of the past (as mentioned on this issue).
Now, onto Avatar examples.
The standard Material-UI Avatar component takes a
src prop which plugs into the Avatar's image
If an image fails to load, it falls back to the children of the component. The
alt prop plugs into the image
To render a letter inside the Avatar component, simply add the letters as children of the component. You can also pass anything else as children,
for example icons, numbers, etc. The children will only be used if an image is not loaded with the
Avatar With Text
To render an Avatar alongside text, simply create a Flexbox component with
align-items: center, and add some
margin-right onto the Avatar.
Inside of your Flexbox, add a
Typography component alongside the
Avatar to create a label. See the above example for how we accomplish this.
To change the color of the Avatar component, you will need to override the styles of the component and set the
background-color. See above examples for how we accomplish this with styled-components.
To set the size of the Avatar component, you will need to override the root styles of the component and set the standard CSS
height to whatever you'd like the size of the Avatar to be.
In our above example, we create a dynamic component to accept a
size prop and then use the Material-UI's spacing function to generate the pixel values. This is optional, you can just use standard pixel values here if you'd like.
To style the Avatar's border, simply set the standard CSS
border attribute on the root Avatar element. In the above example, we do this by wrapping the Avatar with a styled-component.
If an image cannot be loaded, the Avatar will fall back to the children contents. If no children are provided, it will fallback to the first letter of the alt attribute.
The AvatarGroup component can be used to wrap multiple Avatars and provide a condensed view of a
max number of Avatars. Using the
max prop, you can specify how many Avatars you want to show. See the above example for more information.
You can wrap an Avatar component in an
IconButton to get Button functionality. See the above example.