React - Dynamic Image loading using props - javascript

I am attempting to load an image with the src of the image being stored in the this.props.src. The this.props.src outputs the correct name of the img file I would like to load: "koolImg". I am importing the file by: import koolImg from '../img/koolImg.png'. This is the current setup: <img src={this.props.src} alt="noLoad"/>. However, no image is loaded, just the "alt" value is displayed. What am I missing? I am new to React.
I created this react app using the npx create-react-app koolImgApp command, thus using webpack. Running on React 16.4.1 and using Google Chrome 67.

koolImg is just a string which can't be used directly as a src attribute of an img element.
You could map this to the image you have imported by storing the imported image variable in an object, and then accessing that with your src prop string:
Example
import React, { Component } from 'react';
import koolImg from '../img/koolImg.png';
const images = {
koolImg
};
class ImgSrc extends Component {
render() {
return <img src={images[this.props.src]} />;
}
}

Related

Referencing image in assets folder

I have sampleposition.png in my assets folder, and a page called myPage.js in my components folder. How do I reference the sampleposition.png in my assets folder from myPage.js. I've tried src="../assets/sampleposition.png" / but that doesn't seem to be working.
If you are using Create React App, the process is fairly easy and straight-forward.
Are you importing it or doing something like <img src="../whatever/>? You need to be importing so that the build will know how to access it at runtime. See Adding Images, Fonts, and Files
import React from 'react';
import logo from './logo.png'; // Tell webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
}
export default Header;
If you aren't, you need to be serving the content statically and referencing the static content address or use a build/bundle tool to put the content into a place that is known ahead of time which is what the create-react-app tool sets up for you.
Import your image and use it in the code. This should do it according to your requirement.
import React from 'react';
import myImage from '../assets/sampleposition.png';
function YourFunction() {
return
<img src={myImage} alt="myImage" />;
}
export default YourFunction;

Is it possible to destructure image folder files in React Component?

I'm creating a react app. I have an image folder with a few files. In order for React to render the image I have to import it like I import other modules. Something like this:
What I want to do is import the whole image folder, and then find a way to access each file in my Component. for example:
import img from '.../img'
In my JSX, I want to be able to access each of the files from the imported image folder.
Is it possible to do?
You still need to import those images in some place. For cleaner syntax in your main component file, I will group the image files in 1 file
//grouping images in one module. Let's say it is image.js
import imageA from <your-patha>
import imageB from <your-pathb>
import imageC from <your-pathc>
export default {
imgA: imageA,
imgB: imageB,
imgC: imageC
}
//Home component
import Images from '<image.js path>'
const Home = () => {
return (
<img src={Images.imgA} //...other props />
)
}
The best way to do this is you can put all your images in the public folder and refer like below on component.
<img src="/image.jpg" alt="image" />

No response even if img path is specified on React APP

I Launch project with create-react-app. No response even if img path is specified on React APP.
Image is displayed when import statement is used
// not working (1)
<img src={"../img/hoge.png"} />;
//working (2)
import Hoge from "../img/hoge.png";
<img src={Hoge} />
I want to user pattern (1).
Please tell me the solution orz......
Use require for dynamic imports, path like "../img/hoge.png" is not available in runtime because Webpack generates data URI in build time.
import hoge from '../img/hoge.png'; // Tell webpack this JS file uses this image
console.log(hoge); // /hoge.84287d09.png
// For dynamic imports
<img src={require("../img/hoge.png")} />
See Adding images in CRA docs.
If you have a list of potential images at build time, you can use the dynamic import function to load them, although this will return a promise like so:
export class ImageLoader extends React.Component {
constructor(props: any){
super(props);
this.state = {
imagePath: undefined
};
}
render() {
if(this.state.imagePath)
return <img src={this.state.imagePath} />; // Render the image
import(/* webpackMode: "eager" */`../imgs/${this.props.imageName}.png`) // Bundle all paths of images into the bundle
.then((imagePath: string) => {
this.setState({ imagePath}); // Set the new state with the loaded image path
});
return null; // Don't render anything right now since the image hasn't loaded yet.
}
}
This will bundle ALL png images under the imgs directory, use a switch statement with all possible names if that is too much.
See Webpack Documentation and How does Dynamic Import in webpack works when used with an expression?

Image not loading when passing a prop to <img src="this.prop." /> in React

I have an issue regarding a link not loading my image when I pass a prop to the attribute src of img. I have tried wrapping require() around my links and it didn't work.
I have a huge library of products which would be unfeasible to manually import images using the image loader.
Therefore, is there a way to load an image using props inside the src attribute?
I am using NODE_PATH=src/
Thanks for the help!
export const productLib = [{
ID: "001",
name:"product name",
src: "lib/productLib/img/product_name",
color: "",
...
}, {...}]
import React from 'react';
export class Products extends React.Component {
render() {
return(
<div className="products">
<img src={this.props.product.src} width="50" />
<h6>{this.props.product.name}<span className={`block ${this.props.product.color}`}></span></h6>
</div>
)
}
}
As recommended by Xuscrus, I linked my images using the public path. I had to remove my absolute path in order for this solution to work.
I moved all of my images inside a folder named "img" inside the public folder of my create-react-app.
With the example used in my initial statement, here is the easiest solution I found:
import React from 'react';
export class Products extends React.Component {
render() {
return(
<div className="products">
<img src={`/img/${this.props.product.src}.png`} width="50" />
<h6>{this.props.product.name}<span className={`block ${this.props.product.color}`}></span></h6>
</div>
)
}
}
My main reference for my solution was this post (URL method in the correct answer) :
How to do Dynamic images in ReactJS?
I think issue is related with the way you are sending the url to the component.
"lib/productLib/img/product_name" is not an url, not relative url also.
You can use import to get the image.
import React from 'react';
import logo from './logo.png'; // Tell webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
}
export default Header;
If you are using react-create app
they resolve the problem for you:
https://create-react-app.dev/docs/adding-images-fonts-and-files/
I came across a similar issue in fact I was searching for the solution at the moment but figured it out myself I have Images store in a separate folder and I'm importing them in the data file and then Passing it to the component where I needed it, but the image was not displaying.
All I did was
//img is the variable I'm getting the image path at
console.log(img)
That returned
Module {default: "/static/media/svg-1.af890272.svg", __esModule: true,
Symbol(Symbol.toStringTag): "Module"}
default: "/static/media/svg-1.af890272.svg"
Symbol(Symbol.toStringTag): "Module"
__esModule: true
[[Prototype]]: Object
After Getting this in the Module Object I saw the default value so just do
img = img.default
And now you can pass it in src
import React from 'react';
<img src={img} width="50" />

React Native: How to make modular components using local image and data assets?

create-react-native-app v1.0.0
react-native-cli 2.0.1
react-native 0.52.0
Android API 25
I have several JSON files in ./src/data (aliased as data) and images in ./src/assets/images (aliased as images).
I am making a list of images that are filterable and sortable based on the corresponding data. Additionally, I have different types of images the user can toggle between for compact and expanded view.
From my searching it looks like my plan to reference the image path dynamically from a data object property is not possible and I need to do something like:
import image1 from 'images/'image1.png';
import image2 from 'images/'image2.png';
<Image source={some_expression ? image1 : image2} />
or
<Image source={some_expression ?
require('images/image1.png') : require('images/image2.png')} />
That works for the toggle, but I still have the original problem where I can't actually assign image1 and image2 from my data objects such as:
var image1 = "images/" + data.image1.img
where data.image1.img is the filename.
Is there a way around this where I can dynamically reference the local images for the corresponding data in a reusable component?
Short of hardcoding individual components with the images for each data object, I'm at a loss.
I'm new to React and mobile in general so I may have overlooked something in the documentation or online searching.
You can import your local images in parent of your component and use it as a prop.
<Image source={this.props.localImage} />
Where 'localImage' is imported in parent, like in code below and passed as a prop to child (your component).
import localImage from 'images/some-image.png';
This will maintain reusability and works perfectly.
For anyone with the same issue, here is what I did in order to use a string from my JSON data to reference the corresponding image to change what is shown dynamically.
In Images.js import all static images:
const images = {
img1: require('images/img1.png'),
imgNth: require('images/imgNth.png')
}
export default images;
or alternatively
import _img1 from 'images/img1.png';
import _imgNth from 'images/imgNth.png';
const images = {
img1: _img1,
imgNth: _imgNth
}
export default images;
Then where you want to use them i.e. App.js:
import images from 'images/Images';
import data from 'data/Data';
<Image source = {images[data[index].imgName]} />
Where imgName is a property that contains the exact same string value as one of the properties in the imported images i.e. img1 or imgNth in this example.
Regardless of how many images you have, I would suggest writing a simple script to run through your image folder and auto-generate an Images.js type file. It isn't hard to do and will save you a lot of work, especially if you add or remove images regularly during development so you don't have to manually update it each time.

Categories

Resources