It's looks like CardMedia
need an image while component is created. Since I am pulling the image data via componentDidMount
(RestAPI) then the component is already mount.
componentDidMount() {
// get all items via category ID and owner ID
const restApi = new API({ url: 'api' })
restApi.createEntity({ name: 'items' })
// api/items/<categoryId>/<ownerId>
restApi.endpoints.items.getTwo({ id_a: this.props.categoryId, id_b: this.props.ownerId }).then(({ data }) => this.setState({ appData: data }))
}
render() {
const { classes } = this.props;
let classNameHolder = [classes.redAvatar, classes.greenAvatar, classes.blueAvatar, classes.purpleAvatar];
this.state.appData.map(element => {
this.state.images.push(element.imageUrl);
});
return (
<Card>
<CardHeader
avatar={
<Avatar aria-label="Recipe"
className={classNameHolder[Math.floor(Math.random() * classNameHolder.length)]}>
{this.props.userName.charAt(0).toLocaleUpperCase()}
</Avatar>}
title={this.props.userName} disableTypography={true} />
<CardActionArea disabled={this.state.images.length === 1 ? true : false}>
<CardMedia
id={this.props.ownerId}
className={classes.media}
image={this.state.images[this.state.imageIndex]}
onClick={this.handleOnClick} />
</CardActionArea>
</Card >
);
}
}
I can move the all API one level up so I use the props in order to pass data image but I would like to know if you guys have any some elegant solution.
or you can do a simple check in the component itself so to avoid resetting the state, display a mui spinner for instance while content loads this will fix the warning and display nice feedback to the user
<>
{imgUrl ? (
<CardMedia
component="img"
alt="Contemplative Reptile"
height="140"
src={imgUrl}
title="Contemplative Reptile"
/>
) : (
<Spinner />
)}
</>
I had also faced same problem,
I simply added a image link in image
prop of <CardMedia>
.
Like,
<CardMedia
id={this.props.ownerId}
className={classes.media}
image={this.state.images[this.state.imageIndex] || 'https://user-images.githubusercontent.com/194400/49531010-48dad180-f8b1-11e8-8d89-1e61320e1d82.png'}
onClick={this.handleOnClick} />
For me it solved, by just adding a image link.
You can use the Skeleton
component to display a rectangle placeholder with the same height as the image while it is being fetched:
{loading ? (
<Skeleton sx={{ height: 140 }} animation="wave" variant="rectangular" />
) : (
<CardMedia component="img" height="140" image={YOUR_IMAGE_URL} />
)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With