React dynamic mapping image paths from json

1.2k views Asked by At

I have a list of captions displayed from json. I would like to also map the location to local images / or urls in that same json data. So that each iteration of displayed item has its own images included.

The problem is with require js which seems to be working only when im passing into it actual string with location of image. If im trying to pass a reference to node in json that holds the location of that image it does not work. note: some html tags are from materialize.

Does work:

  const imgPath=  require("../images/img1.jpg");
  <img src={ imgPath } alt=""/>

Does not work:

  const imgPath=  require({row.img});
  <img src={ imgPath } alt=""/>

{row.img} is key from json. Is there any way to map image locations like that in json and then use it to display it dynamicly rather than map entire list in static way?

{
    "title":"title caption",
    "note":"Lorem ipsum dolor sit amet....",
    "img":"../images/img1.jpg",
    "iconType":""
}

rendered component: this is how i would like it to work:

    render() {

        let rows = dataJson.map(function(row){
            return <CollapsibleItem header={row.title} icon={row.iconType}>
                    <div>{row.note}</div>
                    <img src={ row.img } alt=""/>
                </CollapsibleItem>
        })

        return (
            <div className="container">
                <div>
                    <Collapsible>
                        {rows}
                    </Collapsible>
                </div>
            </div>
        );
    }

If i import image to the component in static way it does work as well:

    import img01 from "../images/img1.jpg";

and replace {row.img} with {img01}

    <img src={ img01 } alt=""/>

is it possible? i found some examples of importing bunch of images from directory using webpack, but here the difference is that i want to have the paths to images mapped inside of my json, so that i can add images into specific list's item accordingly. Thank You for any thoughts.

0

There are 0 answers