constantlyFlagged
constantlyFlagged

Reputation: 398

How to pass images as a json data in React

Consider the example below:

Currently, I have the Image being imported as shown below:

import TvImage from "./../assets/images/tv.png";

The data is defined as

const data = [
  {
    title: "Enjoy on your TV.",
    subtitle:
      "Watch on smart TVs, PlayStation, Xbox, Chromecast, Apple TV, Blu-ray players and more.",
    image: `${TvImage.src}`,
  },
];

And I am mapping through the data, but the image is not shown. How can I resolve this?

export const Test = () => {
  return (
    <>
      {data.map(({ title, subtitle, image}, key) => (
        <div key={key}>
          <div>
            {title} {subtitle}
          </div>
            <img src={require(image)} alt="" style={{ width: "500px" }} />
        </div>
      ))}
    </>
  );
};



I have also tried the example below, but it does not yield any results:

const data = [
  {
    title: "Enjoy on your TV.",
    subtitle:
      "Watch on smart TVs, PlayStation, Xbox, Chromecast, Apple TV, Blu-ray players and more.",
    image: "./../assets/images/tv.png",
  },
];
export const Test = () => {
  return (
    <>
      {data.map(({ title, subtitle, image}, key ) => (
        <div key={key}>
          <div>
            {title} {subtitle}
          </div>
            <img src={require({image})} alt="" style={{ width: "500px" }} />
        </div>
      ))}
    </>
  );
};

Please note that this is just an example -- this is just a simplified example -- as it is obviously pointless to map through a "data" with one JSON object.

Upvotes: 0

Views: 809

Answers (1)

valentingorr
valentingorr

Reputation: 59

if you are using webpack, you can use the url-loader module

npm i -D url-loader

and add a new rule to your module for images imports

{
  test: (m) => { return /\.(png|jp(e*)g)$/.test(m) },
  exclude: (m) => { return /node_modules/.test(m) },
  use: [{
    loader: "url-loader",
    options: {
      limit: 8000,
      name: "images/[hash]-[name].[ext]"
    }
  }]
}

then import your image in then component:

import TvImage from "./../assets/images/tv.png";

const data = [
  {
    title: "Enjoy on your TV.",
    subtitle:
      "Watch on smart TVs, PlayStation, Xbox, Chromecast, Apple TV, Blu-ray players and more.",
    image: TvImage,
  },
];

export const Test = () => {
  return (
    <>
      {data.map(({ title, subtitle, image}, key) => (
        <div key={key}>
          <div>
            {title} {subtitle}
          </div>
            <img src={image} alt="" style={{ width: "500px" }} /> // use the new image src provided by webpack
        </div>
      ))}
    </>
  );
};

Or, store your images in your public static assets folder

const data = [
  {
    title: "Enjoy on your TV.",
    subtitle:
      "Watch on smart TVs, PlayStation, Xbox, Chromecast, Apple TV, Blu-ray players and more.",
    image: "/images/tv.png",
  },
];

Upvotes: 1

Related Questions