Home > Software engineering >  How to display images from object?
How to display images from object?

Time:07-15

How to display image from object? I was trying to copy relative path, but it's not working for me. Output on browser:

./images/avatars/image-maxblagun.png

data.json

"image": {
          "png": "./images/avatars/image-amyrobson.png",

comment.tsx

import React from 'react';
import data from '../../data.json';

const Comment = () => {
  const mapData = Object.values(data.comments).map((value) => (
    <div key={value.id}>
      <div>
        <img src={value.user.image.png} alt={value.user.image.png} />
        {value.content}
      </div>
    </div>
  ));

  return <>{mapData}</>;
};

export default Comment;

Link to repository: https://github.com/xflameyoke/interactive-comment-section-app

CodePudding user response:

To add to jsecksn's answer, usually you would import images and the like at the top of your file like this. This ensures that when your project is built, webpack will copy the necessary resources etc.

Since your requirement does not allow for such an import, I believe that just copying the resources to the public folder and changing the url's from relative to absolute is the easiest approach.

CodePudding user response:

In that way the images are out of scope for data.json while rendering.

You must move your images folder images/avatars/ to the root of the /public folder in your project.

Meanwhile in data.json, modify the locations for each image, as if it (data.json) were inside the /public folder i.e. "png": "/images/avatars/image-juliusomo.png" and so forth.

  • Related