Unable to view image when using material-ui CardMedia component

Hello, I've encountered a problem with rendering an image in my application. Let me explain the issue in a simplified manner.

So, I have a card component (MyCardComponent) where I need to pass a string prop containing the image file location. The goal is to display this image in a CardMedia element within a material-ui Card.

Unfortunately, despite my efforts, the image is not appearing. How can I resolve this and get the image to render properly? You can check out the recreated issue on CodeSandbox by clicking on this link: https://codesandbox.io/s/image-on-card-kyx0s?fontsize=14&hidenavigation=1&theme=dark

MyCardComponent.js

import React from "react";
import PropTypes from "prop-types";
import "./styles.css";
import { makeStyles } from "@material-ui/core/styles";
import { Card, CardMedia, CardContent } from "@material-ui/core";

const useStyles = makeStyles(theme => ({
  cardRootStyle: {
    minHeight: 300,
    maxHeight: 300
  },
  cardMediaStyle: {
    minHeight: 100,
    maxHeight: 100
  }
}));
export default function MyCardComponent(props) {
  const styles = useStyles();
  return (
    <>
      <Card
        classes={{
          root: styles.cardRootStyle
        }}
      >
        <CardContent>
          <CardMedia image={props.imagePath} />
        </CardContent>
      </Card>
    </>
  );
}

MyCardComponent.propTypes = {
  imagePath: PropTypes.string
};

To use MyCardComponent, you can do so like this:

<MyCardComponent imagePath='/static/sampleimages/cocacola.png'/>

Answer №1

I encountered a couple of issues:

  1. There seems to be a problem with the image path.
  2. You have overlooked using paddingTop. For more information, you can refer to the documentation.

For a working example, check out this link.

Answer №2

Begin by importing your image:

import myImage from 'wherever you stored/myimage.png'

Next, use it in your code like this:

imagePath={myImage}

Now your image is included!

However, it may not be visible as the .MuiCardMedia-root has a height of 0. You will need to address that issue as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In need of a collection of modules determined by a DefinePlugin constant

Currently, I am in the process of constructing a web application utilizing Webpack. However, I have encountered a challenge with a particular aspect of the design - hopefully someone in this forum has experience in similar tasks (or possesses enough knowle ...

The jQuery load() method may not load all elements

I've been struggling with a query issue for quite some time now. I have a Content Management System that I want to integrate into my website, but unfortunately, I am unable to use PHP includes. As an alternative, I decided to utilize jQuery instead. D ...

Both IE and Firefox exhibit erratic behavior when updating the location.hash during the scroll event

In my current project, I am experiencing difficulties updating the location.hash based on which div is currently active in a website with long scrolling. Surprisingly, this functionality works perfectly in Chrome, but fails to work in Firefox and IE. I h ...

Guide to presenting JSON data with ajax

I am trying to dynamically display data based on the selected value from a drop-down list using Ajax's GET method. The idea is to modify the URL by appending the selected item in order to retrieve relevant data from the server: Here is an example of ...

Determine the minimum width in an HTML table's <td> tags

One issue I have encountered is with the columns in my table. I need each column to adjust its width dynamically based on the size of the browser window. However, I also want to ensure that the columns are not too small. To address this, I attempted to se ...

What is the best way to transmit a React context from a lower scope to a higher scope in React?

I have specific requirements regarding database and authentication contexts, as shown below. Please disregard the language aspect, as that is not a concern for me. root.render( <Router> <LangContextProvider> <DBContextContext ...

How can I switch the visibility of two A HREF elements by clicking on one of them?

Let me break it down for you in the simplest way possible. First off, there's this <a href="#" id="PAUSE" class="tubular-pause">Pause</a> and then we have a second one <a href="#" id="PLAY" class="tubular-play">Play</a> Al ...

Issues with Date Format in Material UI DatePicker Component in React

I am encountering an issue with the Material UI DatePicker component in my React project. Even though I have set the date format to "dd/MM/yyyy", the DatePicker is showing dates in the "MM/DD/yyyy" format. Here is the CustomDatePicker Component code: impor ...

Seeking the "onChange" functionality while implementing the "addEventListener" method

I've been busy with a React project lately. Instead of adding 'onChange' to each button within the html object like this: <input type='text' onChange={myFunction} /> I'd prefer to include it in the JS code like so: doc ...

Bidirectional data binding in angular 12 reactive forms

After working with angular for a while, I encountered an issue while trying to implement two-way binding. The code snippet below is where I'm facing difficulty. Since the use of [(ngModel)] has been deprecated in Angular 12 within formGroup, finding ...

What are the recommended guidelines for using TypeScript effectively?

When facing difficulties, I have an array with functions, such as: this._array = [handler, func, type] How should I declare this private property? 1. Array<any> 2. any[] 3. T[] 4. Array<T> What is the difference in these declarations? ...

Issue with Modal Box: Datepicker not Displaying Correctly

I have implemented a modal box in my webpage. When I click on a text field where a datepicker is added, it does not display anything. However, when inspecting the element using Chrome's developer tools, I can see that the 'hasDatepicker' cla ...

Is there a way to seamlessly integrate typeahead.js with jquery.validate?

Currently, I have a website built on ASP.NET MVC 5 which utilizes jQuery validation (specifically 'jquery.validate.js' in the MVC project template). My goal is to implement type-ahead functionality using 'typeahead.js' on an input field ...

Ways to deactivate a Material-UI submit button linked with Formik

Formik integration with Mui for a button component: import React from "react"; import { Button } from "@mui/material"; import { useFormikContext } from "formik"; const ButtonWrapper = ({ children, ...otherProps }) => { ...

Material UI and Next JS do not cooperate well with styles

Help! The global styles are taking over my custom ones. I'm working with Material UI in Next.js. ...

Creating layered images with CSS Grid

Visit this link for more details I've been attempting to create an overlap effect with 3 photos using CSS Grid. My desired outcome looks like this: Click here to see the desired result I followed tutorials that demonstrate the same method, but unfo ...

Should we integrate sailsjs with reactjs or reactjs with sailsjs? What steps can be taken to achieve this integration?

Currently, I am using SailsJS as my web API and ReactJS for the frontend. Can someone please guide me on how to integrate one into the other seamlessly? I am a beginner in this field, so feel free to highlight any mistakes I may have made. ...

Using the ID selector to create a media query

My website is live, and I'm working on making it mobile-friendly. Most of the site works well on mobile, but I'm having trouble centering a jquery lightbox function using media queries. I'm not sure if my syntax is wrong or if there's a ...

What is the best way to have a text field automatically insert a hyphen after specific numbers?

Is there a way to make a text field insert hyphens automatically after certain numbers? For example, when typing a date like 20120212, could we have the input automatically formatted with hyphens after the first 4 digits and the second two, so it displays ...

Is there a way to apply -webkit-line-clamp to this JavaScript content using CSS?

i have a random-posts script for my blogger website <div class="noop-random-posts"><script type="text/javascript"> var randarray = new Array(); var l=0; var flag; var numofpost=10; function nooprandomposts(json){ var total = ...