Home > Enterprise >  Relative path image import from JSON doesn't load in Next.js
Relative path image import from JSON doesn't load in Next.js

Time:11-20

JSON file data fraction:

{
  "categories": [
    {
      "id": 1,
      "category_slug": "food_supplements",
      "title": "Food Supplements",
      "image": "/../../public/images/foodSupplements.png",
    }
  ]
}

Component data fraction that renders the image:

{
  Data.categories.map((category, idx) => {
    return (
      <div key={idx} className="header-categories-container">
        <Image className="header-btn-image" src={category.image} alt="btn-img" width="64" height="64"></Image>
        <Link href={`/${category.route}`}>
          <button className="header-category-button">{category.title}</button>
        </Link>
      </div>
    )
  })
}

The error that occurs in the console is the following: The requested resource isn't a valid image for /../../public/images/foodSupplements.png received text/html; charset=utf-8

Tried putting images into different sources, still didn't work. Tried to import with src=require(...), still the same error.

CodePudding user response:

Try

{
  "categories": [
    {
      "id": 1,
      "category_slug": "food_supplements",
      "title": "Food Supplements",
      "image": "/images/foodSupplements.png",
    }
  ]
}

Analysis
If you have images folder in the public folder then during runtime (in browser) you can fetch the assets from the public folder directly i.e. /images/foodSupplements.png = public/images/foodSupplements.png

CodePudding user response:

Add that file to public folder and change image path to this.

"image": "/foodSupplements.png", should fix the issue

  • Related