Having trouble with a CardMedia component in React not displaying the image properly

I am facing an issue where the images in my project are not showing up. I have tried using an image with a HTTP link and also an image from the project source folder, but both are not loading.

Everything else on the card is loading fine except for the images.

The image location is specified as public/assets/image

In my App.js file:

import React from 'react';
import Products from './components/Products/Products';

function App(props) {
    return (
        <div>
            <Products />
        </div>
    );
}

export default App;

In my Products.jsx file:

import React from 'react';
import { Grid } from '@material-ui/core';
import Product from './Product/Product';
const products = [

    { id: 1, name: 'Shoes', description: 'Running shoes.', price: '$100', image: 'assets/image/run-asics-running-shoes-1636736175.jpeg' },
    { id: 2, name: 'Macbook', description: 'Apple Macbook', price: '$120', image: 'https://images.app.goo.gl/b8T9vFGUzQeHvRmM9' },
]



const Products = () => {

    return (
        <main>
            <Grid container justify="center" spacing={4}>
                {products.map((product) => (

                    <Grid item key={product.id} xs={12} sm={6} md={4} lg={3}>
                        <Product product={product} />
                    </Grid>
                ))}
            </Grid>
        </main>
    )



}

export default Products;

The Product component holds all the products. In Product.jsx file:

import React from 'react';
import { Card, CardMedia, CardContent, CardActions, Typography, IconButton } from '@material-ui/core';
import { AddShoppingCart } from '@material-ui/icons';

import useStyles from './styles';

const Product = ({ product }) => {

    const classes = useStyles();
    return (
        <div>


            <Card className={classes.root}>
                <CardMedia className={classes.media} image='product.image' title={product.name} />
                <CardContent>
                    <div className={classes.cardContent}>
                        <Typography variant="h5" gutterBottom>
                            {product.name}
                        </Typography>
                        <Typography variant="h5" >
                            {product.price}
                        </Typography>


                    </div>
                    <Typography variant="body2" color="textSecondary">
                        {product.description}
                    </Typography>
                </CardContent>
                <CardActions disableSpacing className={classes.cardActions}>
                    <IconButton aria-label="Add to Cart">
                        <AddShoppingCart />
                    </IconButton>
                </CardActions>
            </Card>
        </div>
    );
}

export default Product;

Answer №1

It seems like you are assigning image='product.image', which means it will be set as the exact string "product.image". Did you possibly intend to use image={product.image} instead?

<CardMedia
  className={classes.media}
  image={product.image}
  title={product.name}
/>

Answer №2

In the products array, the image with id:1 is fine

However, the image with id:2 does not have the correct HTTP link; it should be changed to the appropriate image link (on Google Images, right-click and select copy image address)

Within the Product.js file, update the image property of CardMedia to image={product.image} and set its style to style={{minHeight:300}}

Products:

const products = [

    { id: 1, name: 'Shoes', description: 'Running shoes.', price: '$100', image: 'assets/image/run.jpeg' },
    { id: 2, name: 'Macbook', description: 'Apple Macbook', price: '$120', image: 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD...' },
],
 

Product

<CardMedia image={product.image} alt={product.name} style={{minHeight:300}}/>

Answer №3

In order to resolve the issue, simply replace image='product.image' with image={product.image}

        <CardMedia className={classes.media} image={product.image} title={product.name} />
        <CardContent>
            <div className={classes.cardContent}>
                <Typography variant="h5" gutterBottom>
                    {product.name}
                </Typography>
                <Typography variant="h5" >
                    {product.price}
                </Typography>


            </div>
            <Typography variant="body2" color="textSecondary">
                {product.description}
            </Typography>
        </CardContent>

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

Managing user roles uses a combination of node.js, express, sequelize, and react

I found a tutorial on bezkoder that helps with creating user roles. However, I am facing an issue where by default, the user is assigned role 1 [subscriber] during sign-up. As someone who is new to all of this, I'm unsure of how much modification is r ...

After deployment, certain formatting elements appear to be skewed in the React application

After developing a React app with create-react-app, everything was working perfectly. However, upon deployment, I noticed that some styles weren't showing up as expected. The majority of the styling from Material UI is intact, but there are a few dis ...

The issue at hand is that Redux Persist state fails to persist data fetched from an API using

When fetching an API using axios, the action is triggered after the "persist/REHYDRATE" action, resulting in the message "redux-persist/autoRehydrate: 1 actions were fired before rehydration completed...." If I delete tweets one by one and then refresh my ...

Tips for implementing a personalized color scheme with Material UI

Currently, I am attempting to incorporate my own theme into my React Js app with the help of Material UI. If someone could guide me through the process step by step, it would be greatly appreciated. I have limited experience in both ReactJs and Material ...

Challenges with Socket.io in Kubernetes Deployment

I am currently developing a collaborative whiteboard application that utilizes socket.io to communicate with MongoDB. The backend-service, which is in a separate pod from the whiteboard pod, handles all communication. For example: whiteboard app -> backen ...

"Encountering issues with migrating to React Router version 4 using

Currently in the process of migrating to react-router v4, encountered an issue when running the app where "webpack_require.i(...)" is not a function. Seeking guidance on the steps to successfully migrate to router v4. Has anyone else experienced this err ...

The utilization of useState can potentially trigger an endless loop

Currently, I am in the process of developing a web application using Next.js and Tailwind CSS. My goal is to pass a set of data between methods by utilizing useState. However, I have encountered an issue where the application loads indefinitely with excess ...

Can I exclusively utilize named exports in a NextJS project?

Heads up: This is not a repeat of the issue raised on The default export is not a React Component in page: "/" NextJS I'm specifically seeking help with named exports! I am aware that I could switch to using default exports. In my NextJS ap ...

Navigating from an AngularJS page to a ReactJS page on separate ports: A quick guide

I am currently working on an application with a landing page built using AngularJS. The login functionality is also AngularJS-based, and after a successful login, the user's token needs to be stored in local storage and then redirected to the landing ...

Can the labelDisplayedRows be disabled in the table pagination actions of Material UI?

I am currently working on customizing the table pagination actions in Material UI's table and I need to remove the labelDisplayedRows function. My goal is to only show next/previous icons in the footer without the counter (e.g., 1 of 5). I managed t ...

What could be preventing React from successfully uploading images to the server?

My current project involves using React and Express on the backend, with Multer handling uploads. While my server side functions correctly when testing with Postman, I am encountering unexpected results when trying to upload an image from React. Despite su ...

Ways to retrieve Mobx Store by utilizing the following file structure

Imagine having a set of .jsx files that store all your existing data. user-access.jsx import { observable, action, computed } from 'mobx'; export default new class UserAccess{ @observable page_access = []; } stores.jsx import { UserAccess ...

The task of obtaining the remote.origin.url failed as it requires a git repository with a configured origin remote or the 'repo' option must be set

While working on my weather application, I encountered an issue when using the npm run deploy command in the terminal. The error message I received was: Failed to get remote.origin.url (task must either be run in a git repository with a configured origin ...

This particular kind of mistake arises: "sharp" module not detected

Error: The module 'sharp' could not be found. The required stack includes: - D:\Marketing\sbj-react\suburban\node_modules\gatsby-plugin-manifest\safe-sharp.js - D:\Marketing\sbj-react\suburban&bs ...

Using the material-ui checkbox in combination with react-hook-form

Struggling with setting the value of a material-ui checkbox programmatically using react-hook-form's reset method. While my TextField is behaving as expected, the CheckBox is not responding. Here is an example of my code: Check out the code here ...

How do I retrieve and pass values from multiple inputs in my React application?

I've implemented the <autocomplete> as an input field, and I'm currently troubleshooting my submit method by logging values to the console. Unfortunately, I can only submit empty data to my axios instance without any Traceback errors for gu ...

React dynamic table

I've been experimenting with creating a dynamic table in React that allows users to add and delete rows. I need the data entered by the user to be saved, possibly using in-state management so that I can work with it later. Essentially, I'm looki ...

How Axios triggers CanceledError using Abort controller in a React application

I have created a custom axios instance with interceptors to handle authentication requests. The customized axios instance looks like this: const BASE_URL = 'http://localhost:8000'; export const axiosPrivate = axios.create({ baseURL: BASE_URL, ...

Incorporating Material UI components within an embedded Iframe

Trying to implement Material UI components in an Iframe has been a bit of a challenge for me. There is a DemoFrame component provided by Material UI specifically for this purpose, but the styles don't seem to be inserted correctly into the Iframe. To ...

What causes the variation in output results between axios and express when using dot notation?

A geo tool application is in the works, built with reactjs. The concept involves users submitting a city name which then triggers a post request. This request searches through a city list.JSON file to find the corresponding city and returns its geolocation ...