React dynamic mapping image paths from json - javascript

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.

Related

Cannot load images from my desktop on React

enter image description hereI have a folder Images on my desktop with .jpg and .svg on my src file that I would like to add on a component but I cannot load them. I don't understand what I'm doing wrong. Can someone help?
import React from 'react';
import './Banner.css';
const Banner = () => {
return (
<div className="banner">
<img src="../Images/banner.bg.jpg" alt="banner" />
<div className="text">
<img src='../Images/party-icon.svg' alt="party" />
<h3>Let's The Fun Begin!</h3>
<p>Thanks for your order, we'll have it with you as soon as possible.<br></br>
Your order number is #10293838 and a confirmation email has been sent to the address provided.</p>
<p>Order Even Faster in Future</p>
<button className="button">CREATE AN ACCOUNT</button>
</div>
</div>
);
}
export default Banner;
You can import those separate images & use it on src, or you can use require.
If you place your Images directory inside public folder then you can access your images directly like this
src="/Images/banner.bg.jpg"
Check the answers of this question (Correct path for img on React.js), I think that may help you to understand those solutions better.
1 - Your images should sit inside your project source (usually in a 'assets'/'images') folder.
2 - Make sure that the source path in <img src='../Images/party-icon.svg' alt="party" /> is relative to the current file and points to the party-icon.svg sitting in your assets folder.
You may import the pic on top like this:
import bg from '../Images/banner.bg.jpg'
then add your pic like this:
<img src={bg} alt="banner" />
you can do the same thing for other pics. Instead of bg you can write anything you want. Choosing appropriate names for different pictures can be better.
Good luck :)

React Image Source

I can't seem to figure out why my relative path image loading doesn't work.
The file structure where the assets are located are within the src folder in my working directory, but they don't seem to be working.
If I directly import import image from '../Assets/color/cloudy.svg'it works but otherwise it doesn't work. I don't want to directly import as the logic is to query the appropriate image (27 total images) based off the value passed through props.
Any help would be appreciated.
export default function Main(props) {
const { weather } = props;
// let img_src = weather.weather_code.value;
const img_src = '../Assets/color/cloudy.svg';
console.log(img_src);
return (
<div className="center">
<div className="title">
<span className="currently">
<span>
<img src={img_src} alt="weather" />
</span>
<span className="description">
<span className="summary">
<span className="label">Temperature:</span>
<span>
{weather.temp.value} {weather.temp.units}
</span>
</span>
<span className="summary-high-low">
<span className="label">Feels Like:</span>
<span>
{weather.feels_like.value} {weather.feels_like.units}
</span>
</span>
</span>
</span>
</div>
</div>
);
}
One simple way is to create a folder under the public/ folder on your app, and put all images there.
and then in dev mode you can acc them like this:
<img src="/imageFolder/cloudy.png" alt="cloudy" />
This should work just fine in production too, because the folder under public is added to the project.
If you are using webpack, you need to import the image :
<img src={require('images/06.jpg')} alt="product" />
As your images data is dynamic, directly specifying the import path like
<img src={require(image)} alt="product" />
doesn't work.
However you can import the image by making use of template literals like
<img src={require(`${image}`)} alt="product" />

React lazy load image in a component that is passed image source as a property

I have a React app created with create-react-app. It contains the standard src/ directory and I have created a src/assets/home/ directory where I have saved image files that I intend to use in my project. I am not sure how to get the image referencing correctly within components in my app.
I have the following component that I pass a set of properties whose path is src/scenes/Home/InfographicSection/InfographicBlock/InfographicBlock.js:
<InfographicBlock
title="Some Title"
description="some text"
imgPath="../../../../assets/home/home-logo.png"
/>
The InfographicBlock uses the library react-lazyload (https://www.npmjs.com/package/react-lazyload):
import React from 'react';
import LazyLoad from 'react-lazyload';
const InfographicBlock = (props) => (
<div className="infographic-block columns">
<LazyLoad height={200}>
<img src={require(`${props.imgPath}`)} alt="" />
</LazyLoad>
<div className="content-container column">
<h2 className="subtitle">{props.title}</h2>
<p>{props.description}</p>
</div>
</div>
);
export default InfographicBlock;
The image referencing works great if I add the string path directly to the image tag like so:
<img src={ require('../../../../assets/home/home-logo.png') } />
However seeing as this is a component, I want to pass in the property as a variable to reuse the component.
I have tried variations of this without success:
<img src={require(`${props.imgPath}`)} alt="" />
Any help is appreciated.
What i did was import the image first.
import product1 from './Images/female_sport3.jpg'
<ProductPage currency={currency} currencyRate={currencyRate} product1={product1}></ProductPage>
Inside ProductPage.js
const {currency, currencyRate, product1} = props
<img src={product1} alt=""></img>
This is the reference for import image: https://www.edwardbeazer.com/importing-images-with-react/

How to load and display an image using react functions (not class)?

I am new to react.js and JS in general.
I am looking for an example of code that:
uses react functions, not classes.
let the user upload an image using
then display that image on the screen
Thanks in advance.
First image should copy in to project path and import that into your page
import img from "../../assets/img/logo.svg";
render() {
return (
<div className="content" >
<img id="logo-img" src={img} alt="logo" />
</div>
)
}

Mustache flat array into nested elements

I'm isolating the problem and creating a simple case in here. It's basically an Image Accordion (CSS3 animation based) and in order to use this plugin my HTML structure has to be nested as shown below. In their samples the HTML was hardcoded - I need to use JSON data to generate the output.
Suppose an object like this,
[{imageurl:"link1"}, {imageurl: "link2"}, {imageurl: "link3"}]
I want the output to be
<figure>
<img src="link1" />
<figure>
<img src="link2" />
<figure>
<img src="link3 />
</figure>
</figure>
</figure>
I'm trying to think what kind of template can help to achieve this?
Because the Mustache language is "logic-less", views that require logic or complex nesting may need to be broken up into different views and included via partials or created outside of Mustache and then reinserted.
Anyhow, one way to produce the view that you desire is by reversing the array and working inside-out to nest the figures (jsfiddle):
<!-- If your desired output is so:
<figure>
<img src="link1">
<figure>
<img src="link2">
<figure>
<img src="link3">
</figure>
</figure>
</figure>
-->
<script id="entriesTemplate" type="text/x-mustache-template">
<figure>
<img src="{{{imageurl}}}">
{{{figure}}}
</figure>
</script>
You can then nest the above template via a small snippet of JS:
var figs = [
{url: "http://placehold.it/10x10"},
{url: "http://placehold.it/10x10"},
{url: "http://placehold.it/10x10"}
];
var ft = document.querySelector('#entriesTemplate').innerText.trim();
Mustache.parse(ft);
console.log(
figs.slice(0) // Make a copy of the array as the next call to `.reverse()` will work in situ
.reverse()
.reduce(function (previous, current, index, array) {
return fig = Mustache.render(ft, {
imageurl: current.url,
figure: previous
});
}, undefined)
);
When you pass undefined into the first template render, Mustache will produce no nested figure. Each subsequent render you are passing the output from the past to the outer figure etc. Instead of logging the value, you can then insert the chunk of HTML as need.

Categories