I'm new to React and have hit a roadblock. Basically, I'm trying to create a simple reusable component. I am using MUI and want to create an avatar component to be called anywhere with a different image for when it is called. I want to be able to call in an argument when declaring the component in various pages. Please help
import * as React from 'react';
import Avatar from '@mui/material/Avatar';
import Stack from '@mui/material/Stack';
import frankieAvatar from '/Users/rodriguezmedia/Desktop/react-counter-app/src/images/oink.png';
import { AvatarGroup } from '@mui/material';
const designerOne = {
src: frankieAvatar
}
export default function AvatarDesigners() {
return (
<Avatar src={designerOne.src}></Avatar>
);
}
CodePudding user response:
you can do it simply like below.
import * as React from 'react';
import Avatar from '@mui/material/Avatar';
import Stack from '@mui/material/Stack';
import { AvatarGroup } from '@mui/material';
export default function AvatarDesigners({src}) {
return (
<Avatar src={src}></Avatar>
);
}
The component that you use it:
import * as React from 'react';
import frankieAvatar from '/Users/rodriguezmedia/Desktop/react-counter-
app/src/images/oink.png';
import AvatarDesigners from './AvatarDesigners'
const designerOne = {
src: frankieAvatar
}
export default function Profile() {
return (
<div>
<AvatarDesigners src={designerOne.src}></Avatar>
</div>
);
}
CodePudding user response:
image avatars can be created by passing standard img props src or srcSet to the component.
<Avatar alt="Remy Sharp" src="/static/images/avatar/1.jpg" />
<Avatar alt="Travis Howard" src="/static/images/avatar/2.jpg" />
<Avatar alt="Cindy Baker" src="/static/images/avatar/3.jpg" />
CodePudding user response:
If there is an error loading the avatar image, the component falls back to an alternative in the following order: the provided children the first letter of the alt text a generic avatar icon
<Avatar
sx={{ bgcolor: deepOrange[500] }}
alt="Remy Sharp"
src="/broken-image.jpg"
>
B
</Avatar>
<Avatar
sx={{ bgcolor: deepOrange[500] }}
alt="Remy Sharp"
src="/broken-image.jpg"
/>
<Avatar src="/broken-image.jpg" />