Search code examples
reactjsreact-bootstraprequire

Require inside a react component error 'Cannot find module'


I am trying to require pictures from local path:

{userImages.map((image) => {
                  return (
                    <Carousel.Item key={image.id}>
                      <Card.Img src={require(image.picture)} />

The value inside the variable looks like this:

../../media/female/f1.jpg

The error I am receiving:

Cannot find module '../../media/female/f1.jpg'

I tried another solution to require before the return like this:

const pic = require(userImages[0].picture);

still received the same error. If I user require at the top of the component's file it does require correctly from this path.


Solution

  • Found the solution from this link : Dynamically Loading Local Images with ReactJS

    it was to create context for the folder of images first at the top of the file like this:

    const maleImages = require.context("../../media/male", true);
    const femaleImages = require.context("../../media/female", true);
    

    Then within the return include the image like this:

    {userImages.map((image) => {
                      let img;
                      switch (user.gender) {
                        case "female":
                          img = femaleImages(image.picture);
                          break;
                        case "male":
                          img = maleImages(image.picture);
                          break;
                        default:
                      }
    

    Thanks guys for your help!