0

i have a json file containing array of object such that:

[
    { 
      "id": 1,
      "title": "first title",
      "description":"first descript",
      "image":"/assets/Images/myimage-1.jpg"
    },
 { 
      "id": 2,
      "title": "second title",
      "description":"second descript",
      "image":"/assets/Images/second.jpg"
    },
   
  ]

i have the following function in jsx

export default function myfunc({task}) {
    return (
        <ul>
            {tasks.map(task => <div key={task.id} >{task.title}{task.description}</div> )} ; 
            {tasks.map(task => <img src={task.image} key={task.id}></img> )}  

        </ul>
    )
}

which when executed parses the text content first then the image content, due to the need for img tag how can i make it so that it is parsing the image source and text in one go using map? while being able to assign classes to them?

i found a similar question from years ago but that one is unanswered as well. React dynamic mapping image paths from json

Mel
  • 174
  • 1
  • 11

1 Answers1

1

Here you go

First, I've created a one js file which map all the image files that I want to use, something like

export default {
  "1.png": require("./1.png"),
  "2.png": require("./2.png")
};

Then, next step,I've imported the mapping file and change json a bit

import images from "./assets"; // <----- imported

const tasks = [
  {
    id: 1,
    title: "first title",
    description: "first descript",
    image: "1.png" // <------- changed here
  },
  {
    id: 2,
    title: "second title",
    description: "second descript",
    image: "2.png" // <------- changed here
  }
];

Final Step :

{tasks.map(task => (
    <img alt="" width="250" 
         src={images[task.image]} // <----- HERE
         key={task.id} />

))}

WORKING DEMO :

Edit #SO-image-mapping

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122