I have an Avatar Component
that I have created, its a very basic component that displays an icon and some text. This is the code for the component.
import React from "react";
import PropTypes from "prop-types";
import { withStyles, Avatar, Typography } from "@material-ui/core";
import avatar_placeholder from "../images/avatar_man.svg";
const styles = theme => ({
row: {
display: "flex",
flexDirection: "row",
alignItems: "center"
},
avatar: {
width: 50,
height: 50,
marginRight: "2%"
},
subtitle: {
opacity: 0.5
}
});
const customAvatar = props => {
const { classes, name, subtitle } = props;
return (
<div className={classes.row}>
<Avatar alt={name} src={avatar_placeholder} />
<div>
<Typography variant="title">{name}</Typography>
<Typography variant="body2" className={classes.subtitle}>
{subtitle}
</Typography>
</div>
</div>
);
};
customAvatar.propTypes = {
classes: PropTypes.object.isRequired,
name: PropTypes.string.isRequired,
image: PropTypes.string,
subtitle: PropTypes.string
};
customAvatar.defaultProps = {
name: "John Doe",
subtitle: ""
};
export default withStyles(styles)(customAvatar);
The Avatar
component is the child component of a parent, the code that follows is how the Avatar
component is used in the parent.
import React from "react";
import PropTypes from "prop-types";
import {
withStyles,
Card,
CardContent
} from "@material-ui/core";
import AvatarProfile from "./AvatarProfile";
const styles = {
cardContent: {
},
AvatarDiv: {
backgroundColor: "red"
}
};
const ItemCardWithCheckbox = props => {
const { classes, name, subtitle } = props;
return (
<Card>
<CardContent className={classes.cardContent}>
<AvatarProfile
name={name}
subtitle={subtitle}
className={classes.AvatarDiv}
/>
</CardContent>
</Card>
);
};
ItemCardWithCheckbox.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(ItemCardWithCheckbox);
As you can see I am trying to apply the AvatarDiv
style for the Avatar
component ie, I would like the backgroundColor
of the Avatar
component to be red but that's not happening, I am using Material UI. My guess is either the style props aren't being passed properly to the Avatar
component or I'm not applying the style correctly.
You are passing AvatarDiv as 'className' prop. You are not applying the class here, as AvatarDiv is a custom component.
<AvatarProfile
name={name}
subtitle={subtitle}
className={classes.AvatarDiv}
You have to pass it as props and use that prop to apply the style in the child component. I have done something similar in the codesandbox, where i change the color to orange for the button and pass it as prop to child component . Please check - https://codesandbox.io/s/lyxz92m7nl