admin管理员组

文章数量:1133893

I used other react components before, they mostly have their own Image component, but I can't find that in Material-UI?

Or is it done via CardMediaAPI? or simply use tags? Thanks!

I used other react components before, they mostly have their own Image component, but I can't find that in Material-UI?

Or is it done via CardMediaAPI? or simply use tags? Thanks!

Share Improve this question asked Apr 17, 2020 at 3:27 purepure 1,1452 gold badges7 silver badges8 bronze badges
Add a comment  | 

12 Answers 12

Reset to default 174

Another option (at least in v5) is to use the Box component and select the underlying html element to be img as given in the example below (copied from official docs for v5)

<Box
  component="img"
  sx={{
    height: 233,
    width: 350,
    maxHeight: { xs: 233, md: 167 },
    maxWidth: { xs: 350, md: 250 },
  }}
  alt="The house from the offer."
  src="https://images.unsplash.com/photo-1512917774080-9991f1c4c750?auto=format&w=350&dpr=2"
/>

There is no such specific custom img component avaiable with material-ui.

But you can use the simple html img component inside another wrapper components to create custom img component by your own. e.g

<Paper variant="outlined">
   <img src="url" />
</Paper>

Also <CardMedia/> component has to be used with in conjunction with <Card/> component. Another such component which uses image is <Avatar> component.

<Avatar alt="Example Alt" src="/static/images/avatar.jpg" />

Material-ui recommends using Material-ui-image, you have to install it separately but I have really enjoyed using it. After installing, as expected, it's simply:

import Image from "material-ui-image";
...
<Image src="image/src/" />

Using mui's Box component is a good starting point. From there one can easily build its own reusable component without the need for another dependency. Try something like:

import {Box, BoxProps, } from "@mui/material";

type ImgProps = {
    alt: string;
    src: string;
    // add more HTML img attributes you need
}

export const Img = (props: BoxProps & ImgProps) => <Box component='img' {...props} />;

While I am answering this question, the latest version of MUI is 5.2.2 and there is no exact image component, but MUI had mentioned two third-party provided image components. One is mui-image and another one is material-ui-image. According to MUI, "mui-image is the only MUI image component to satisfy the Material guidelines for loading images" .

You can easily install mui-image by following few steps:

Install:

npm i mui-image
//or
yarn add mui-image

Import:

import Image from 'mui-image'
// or
import { Image } from 'mui-image'

Use:

<Image src="my-image.png" />

For details about mui-image props and more check npmjs package docs here.

You can use CardMedia from Material UI as below. Please see the section Complex Interaction in Material UI Example

<CardMedia
    className={classes.media}
    image="/static/images/cards/paella.jpg"
    title="Paella dish"
/>

Use the Avatar component

<Avatar variant={"rounded"} alt="The image" src={url} style={{
    width: 200,
    height: 200,
  }} />

Docs

Use Box component with component prop:

 <Box component="img" src={image} alt={caption} sx={{ height: "50px", width: "auto" }} />

I prefer using styled to create my own image component:

import { styled } from '@mui/material/styles';

const StyledImg = styled('img')({});

// Or with a default style

// const StyledImg = styled('img')({
//   display: 'block',
// });

<StyledImg
  src={imagePath}
  alt='my Image'
  sx={{
    width: 50,
  }}
/>

Use the CardMedia component

const [previewImage, setPreviewImage]=  useState<any>();

const { getRootProps, getInputProps } = useDropzone({
    accept: "image/*",
    onDrop: (acceptedFiles) => {
        setPreviewImage(URL.createObjectURL(acceptedFiles[0]));
    },
});

<CardMedia
   component="img"
   sx={{
   height: 233,
   width: 350,
   maxHeight: { xs: 233, md: 167 },
   maxWidth: { xs: 350, md: 250 },
   }}
   src={previewImage}
/>
                                

More details

My suggestion is to go with the CardMedia component provided by @mui/material instead of using plain HTML tags. You have these abilities and more :

  • onLoad and onError props are used to log messages to the console when the image is successfully loaded or if an error occurs while loading it, respectively. This can be helpful for debugging purposes. Or, you can use your custom functions on these props.
  • you can use the sx attribute to style your image and at the same time, make styles for different breakpoints.
  • you can define the HTML tag type using the component attribute
  • the image attribute is used to display the image
  • alt attribute for alternative text incase if the image doesn't show up.

Here is a code example on how to use images using the CardMedia component

          <CardMedia
            component="img"
            image={sampleImage}
            onLoad={() => console.log("this is loading")}
            onError={() => console.log("this is error")}
            alt="This is a sample image"
            sx={{
              maxWidth: {
                xs: "100%",
                sm: "500px",
              },
              objectFit: "cover",
            }}
          />

Sorry, no actually.

but we have two alternative approaches to mimic it.

Here is a github issue about your request.

  • one approach: convert it into styled-component
const Img = styled("img")({})
  • another approach: utilize material component Box's component property
<Box component="img" sx={{/* your styles */}} />

本文标签: javascriptDoes Material UI have an Image componentStack Overflow