React dynamic mapping image paths from json

瘦欲@ 提交于 2020-07-19 19:01:27

问题


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.

来源:https://stackoverflow.com/questions/48743952/react-dynamic-mapping-image-paths-from-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!