Why I cant see image in the example of material -ui-v3.2.0 "Image avatars "
Asked Answered
I

1

5

This example "Image avatars" https://material-ui.com/demos/avatars/ comes from material-ui v3.2.0 website but somehow I can't see the image when I implement.

Why I can't see image in the example of material -ui-v3.2.0 "Image avatars "?

In the examples 'icon avatars' and 'Letter avatars' I can see the image. I use the create-react-app 'react-scripts': '^2.0.4', but also tried on 'react-scripts': '^1.1.5' but nothing works.

PFB below code:

import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { withStyles } from '@material-ui/core/styles';
import Avatar from '@material-ui/core/Avatar';

const styles = {
  row: {
    display: 'flex',
    justifyContent: 'center',
  },
  avatar: {
    margin: 10,
  },
  bigAvatar: {
    width: 60,
    height: 60,
  },
};

function ImageAvatars(props) {
  const { classes } = props;
  return (
    <div className={classes.row}>
      <Avatar alt="Remy Sharp" src="/static/images/remy.jpg" className={classes.avatar} />
      <Avatar
        alt="Adelle Charles"
        src="/static/images/uxceo-128.jpg"
        className={classNames(classes.avatar, classes.bigAvatar)}
      />
    </div>
  );
}

ImageAvatars.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(ImageAvatars);
Indicant answered 10/10, 2018 at 7:56 Comment(0)
A
16

You need to import it. Just passing path directly to src won't work. Below are two ways to render images in react

Using import

import uxceo from "/static/images/uxceo-128.jpg";
import remy from "/static/images/remy.jpg";

<Avatar alt="Remy Sharp" src={remy} className={classes.avatar} />
<Avatar
    alt="Adelle Charles"
    src={uxceo}
    className={classNames(classes.avatar, classes.bigAvatar)}
  />

OR Using require

<Avatar alt="Remy Sharp" src={require("/static/images/remy.jpg")} className={classes.avatar} />
<Avatar
    alt="Adelle Charles"
    src={require("/static/images/uxceo-128.jpg")}
    className={classNames(classes.avatar, classes.bigAvatar)}
  />
Assuan answered 10/10, 2018 at 8:0 Comment(4)
Just to add he may also need to add file-loader to his webpack config to get the imports to work.Ref
@Ref Looks like he created app using create-react-app. So do we still need webpack ? Aren't they pre-configured by create-react-app?Assuan
Everything works. Thank you very much for the quick response.Vanzandt
@Indicant You are welcome :) Please do upvote and accept answer so that it will help future readersAssuan

© 2022 - 2024 — McMap. All rights reserved.