Home > Software engineering >  Image not displaying after being passed as prop to child component
Image not displaying after being passed as prop to child component

Time:12-14

I am trying to display an image i am passing to a prop but getting the error

Cannot find module '../images/blah-blah.jpg'

Tried looking about online but can't figure out what i am doing wrong. New to react, so sorry if this is really simple.

<ProfileCard 
   image='../images/blah-blah.jpg' 
   name='Name' 
   title='(CEO)'/>
import React from "react"
import Card from 'react-bootstrap/Card';

function ProfileCard({image, name, title}) {
  return (
    <Card style={{ width: '22rem' }}>
    <Card.Img variant="top" src={require(image)} /> 
    <Card.Body>
      <Card.Title>{name}</Card.Title>
      <Card.Text>
        {title}
      </Card.Text>
    </Card.Body>
  </Card>
  )
};

export default ProfileCard;

Folder structure

enter image description here

CodePudding user response:

You need to import the image like this in the parent component like this

import ImageFile from '../images/blah-blah.jpg' 

<ProfileCard 
   image={ImageFile}
   name='Name' 
   title='(CEO)'
/>

and then you can use it this way in your ProfileCard component

import React from "react"
import Card from 'react-bootstrap/Card';

function ProfileCard({image, name, title}) {
  return (
    <Card style={{ width: '22rem' }}>
    <Card.Img variant="top" src={image} /> 
    <Card.Body>
      <Card.Title>{name}</Card.Title>
      <Card.Text>
        {title}
      </Card.Text>
    </Card.Body>
  </Card>
  )
};

export default ProfileCard;

The require is not necessary, and you can rename ImageFile to whatever you want.

Also, make sure the path is right. You can look at a working sample on this codesandbox https://codesandbox.io/s/kind-shtern-qx23ev?file=/src/index.js

  • Related