Home > Mobile >  Cannot find module '../../assets/women.jpg' in react while importing dynamically
Cannot find module '../../assets/women.jpg' in react while importing dynamically

Time:12-19

I have a data.js file in the assets and it has some images with infos, but when I try to pass the path of the image to the prop I get the error above. I checked the path and it works fine.

This is data.js

export const categories = [
  {
    id: 1,
    title: "WOMEN",
    img: "../../assets/women.jpg",
  },
  {
    id: 2,
    title: "MEN",
    img: "../../assets/men.jpg",
  },

  {
    id: 3,
    title: "CHILDREN",
    img: "../../assets/children.jpg",
  },
];

and this is my component

import React from 'react'
const CategoryItem = ({item}) => {
    return (
        <div className='category-item-container'>
            <img src={require( `${ item.img }`)} />
            <p>
                {item.img}
            </p>
        </div>
    )
}

export default CategoryItem

CodePudding user response:

In react, we want to store our filepaths as variables that we can then inject into our JSX whenever we want. I'd make sure to have import statements above your exported array. Here are the React docs with concise examples.

https://create-react-app.dev/docs/adding-images-fonts-and-files/

CodePudding user response:

my images where in my src file so i ended moving them to public then I changed their path in data so instead of img: "../../assets/women.jpg", I used img: "women.jpg", so I didn't need to use require anymore and just used <img src={ item.img } alt='img' /> and it works fine.

CodePudding user response:

Try to import your image


import women from "../../assets/women.jpg"
import men from "../../assets/men.jpg"
import children from "../../assets/children.jpg"
export const categories = [
  {
    id: 1,
    title: "WOMEN",
    img: women,
  },
  {
    id: 2,
    title: "MEN",
    img: men,
  },

  {
    id: 3,
    title: "CHILDREN",
    img: children,
  },
];

const CategoryItem = ({item}) => {
    return (
        <div className='category-item-container'>
            <img src={item.img} />
            <p>
                {item.img}
            </p>
        </div>
    )
}

export default CategoryItem
  • Related