How to load local images in React through props? - reactjs

I have placed downloaded images in an images folder inside my public folder. The images are numbered from 1 to 10.
In my App.js file I am passing the id of each image to Component.js.
return(
<div>
{info.map((users, i) => {
return(
<Component key={i} id={info[i].id} />
)
})}
</div>
)
And in the Component.js file, I am rendering an image like this:
<img alt='image' src='/images/{this.props.id}.jpg'/>
My vision is that I will send an id through props from App.js and in Component.js I will use that id for {this.props.id}.jpg to display the id's respective image. The page is loading and there are no errors showing up but I am not able to see the images. I then changed the images folder's location and tried doing this:
<img alt='image' src={require(`D:/project-name/src/images/${this.props.id}.jpg`)}/>
But still facing the same issue. Please help me solve this issue.

The issue is in your image tag. Try making the string a template string and don't forget to add the missing dollar sign before {this.props.id}.
<img alt='image' src={`/images/${this.props.id}.jpg`} />

Related

Can't play audio using React [duplicate]

I have some problem with my images on my react project. Indeed I always thought that relative path into src attribute was built on the files architecture
Here my files architecture:
components
file1.jsx
file2.jsx
file3.jsx
container
img
js
...
However I realized that the path is built on the url. In one of my component (for example into file1.jsx) I have this:
localhost/details/2
<img src="../img/myImage.png" /> -> works
localhost/details/2/id
<img src="../img/myImage.png" /> -> doesn't work, images are not displayed
How is it possible to solve this problem? I want that in any form of routes handled by react-router, all images can be displayed with the same path.
In create-react-app relative paths for images don't seem to work. Instead, you can import an image:
import logo from './logo.png' // relative path to image
class Nav extends Component {
render() {
return (
<img src={logo} alt={"logo"}/>
)
}
}
If you used create-react-app to create your project then your public folder is accessible. So you need to add your image folder inside the public folder.
public/images/
<img src="/images/logo.png" />
You're using a relative url, which is relative to the current url, not the file system. You could resolve this by using absolute urls
<img src ="http://localhost:3000/details/img/myImage.png" />
But that's not great for when you deploy to www.my-domain.bike, or any other site. Better would be to use a url relative to the root directory of the site
<img src="/details/img/myImage.png" />
With create-react-app there is public folder (with index.html...).
If you place your "myImage.png" there, say under img sub-folder, then you can access them through:
<img src={window.location.origin + '/img/myImage.png'} />
If the image is placed inside the 'src' folder, use the following:
<img src={require('../logo.png')} alt="logo" className="brand-logo"/>
Make an images folder inside src(/src/images) And keep your image in it. Then import this image in your component(use your relative path). Like below-
import imageSrc from './images/image-name.jpg';
And then in your component.
<img title="my-img" src={imageSrc} alt="my-img" />
Another way is to keep images in public folder and import them using relative path. For this make an image folder in public folder and keep your image in it. And then in your component use it like below.
<img title="my-img" src='/images/my-image.jpg' alt="my-img" />
Both method work but first one is recommended because its cleaner way and images are handled by webpack during build time.
Some older answers din't work, others are good but won't explain the theme, in summary:
If image is in 'public' directory
Example: \public\charts\a.png
In html:
<img id="imglogo" src="/charts/logo.svg" />
In JavaScript:
Create image to new img, dynamically:
var img1 = document.createElement("img");
img1.src = 'charts/a.png';
Set image to existing img with id as 'img1', dynamically:
document.getElementById('img1').src = 'charts/a.png';
If image is in 'src' directory:
Example: \src\logo.svg
In JavaScript:
import logo from './logo.svg';
img1.src = logo;
In jsx:
<img src={logo} />
I have used it this way and it worked perfectly
import Product from "../../images/product-icon.png";
import { Icon } from "#material-ui/core";
<Icon>
<img src={Product} style={{ width: "21px", height: "24px" }} />
</Icon>
Adding file-loader npm to webpack.config.js per its official usage instruction like so:
config.module.rules.push(
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
);
worked for me.
Import Images in your component
import RecentProjectImage_3 from '../../asset/image/recent-projects/latest_news_3.jpg'
And call the image name on image src={RecentProjectImage_3} as a object
<Img src={RecentProjectImage_3} alt="" />
A friend showed me how to do this as follows:
"./" works when the file requesting the image (e.g., "example.js") is on the same level within the folder tree structure as the folder "images".
Place the logo in your public folder under e.g. public/img/logo.png and then refer to the public folder as %PUBLIC_URL%:
<img src="%PUBLIC_URL%/img/logo.png"/>
The use of %PUBLIC_URL% in the above will be replaced with the URL of the public folder during the build. Only files inside the public folder can be referenced from the HTML.
Unlike "/img/logo.png" or "logo.png", "%PUBLIC_URL%/img/logo.png" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running npm run build.
If your page url contains multiple / then in src go back / count minus 1 times.
For example page url http://localhost:3000/play/game/ then src url must be ../your-image-folder/image-name. And your your-image-folder must be in public folder.
I create my app with create-react-app and I use require instruction if I want to change dynamically my image src:
export const MyComponent = () => {
const [myImg, setMyImg] = useState(require('./path/to/my/img'));
const handleClick = () => {
setMyImg(require('./path/to/other/img'));
}
return (
<div>
<img src={myImg} alt='myImg' />
<button onClick={handleClick}>Click me!<button/>
<div>
)
}

Dynamic image src linking in react doesn`t work (multiple tries)

In my project I need to link a img src dynamically.
This is the whole project structure:
I have tried multiple ways to link up my imag src in the follwing component, as you can see in the out commented part of my code.
The path itself cannot be the problem because the third try, which I cannot use cause its not dynamic, works very well.
What am I doin wrong?
import React from 'react';
import * as CommentStyles from './comment.module.scss';
// Only this works
import Image from '../../../../assets/image-anne.jpg';
function Comment({comment}) {
return (
<div>
<div className={CommentStyles.firstRow}>
{/* first try - didn`t work*/}
{/* <img src={require('../../../../assets/image-anne.jpg')} /> */}
{/* second try - didn`t work*/}
{/* <img src={'../../../../assets/image-anne.jpg'}/> */}
{/* third try - didn`t work*/}
<img src='../../../../assets/image-anne.jpg'/>
{/* fourth try-works: */}
{/* <img src={Image}/> */}
<div className="firstFlexItem">
<div className="name Username">
{comment.user.name} <br/>
{comment.user.username}
</div>
</div>
<p>
Reply
</p>
</div>
</div>
)
}
export default Comment
I have now put the jpg in the public folder and it doesn`t work:
I'm assuming you have created your reactjs project using the create-react-app command.
Since you want to dynamically set the image src attribute, the workaround would be to add the image or images inside the public folder as advised here in the official documentation : https://create-react-app.dev/docs/using-the-public-folder/#when-to-use-the-public-folder
Then just use
<img src={`image-anne.jpg`} />
Where src has the path to your image relative to the public folder. This can also be dynamically set and will work just fine
NOTE : If this doesn't work, use
<img src={process.env.PUBLIC_URL + '/image-anne.jpg'} />
And make sure you kill the current session and restart your app using npm start or yarn start if you still can't see the image.
Screenshot from above link :

Display an image from url in ReactJS in tsx file

I want to display an image from a URL in React. For example, I want this image in tsx file
http://d1cs08zudd3ykv.cloudfront.net/dev/img/arrow-up.svg
to be displayed in reactJS. When I am trying to use requires not working but require is working with the local path. Is it possible to do or Is there any other way to do it? And how to do it?
Just set image src to URL of the image
const Component = (props) => {
return (
<div>
<img src="http://d1cs08zudd3ykv.cloudfront.net/dev/img/arrow-up.svg" alt="" />
</div>
);
};

onError does not load the default image - React

What I am trying to achieve is that a particular image should be loaded for a div, when present. A default image should be loaded for all other divs for whom specific (depending on the name) image is not present.
const defaultImg = require('../images/default.jpg');
But this is the value that console returns for defaultImg - "image /static/media/default.47ce6e77.jpg"
<img src={require(`../images/${imageUrl}.jpg`)} //if I remove ther require form here then the default image is loaded for eveerything, even when the particular image is present.
onError={(event) => event.target.setAttribute("src", {defaultImg})} alt="" />
Instead of the defulat image getting loaded, it throws
Error: Cannot find module './<image-name>.jpg'
I also tried using React Image Fallback
{/* <ReactImageFallback
src={require(`../images/${imageUrl}.jpg`)}
fallbackImage={defaultImg}
initialImage="loader.gif"
alt="A cool image should be here"
className="project-pic"
/> */}
Doesn't work any different.
If const defaultImg = require('../images/default.jpg');
Why does it become /static/media/default.47ce6e77.jpg ?
Check your source in devtool. Your img might be showing as <img src="[object Object]" alt="">.
Replace your onError with onError={(event) => event.target.setAttribute("src", defaultImg)}. You are passing defaultImg as object.
Considerusing the fallback image:
<img src={imagesrc}
onError={(e) => {
e.target.onerror = null
e.target.src = fallbackImg}
} />

Passing local image file path via object value to React prop not working?

I have a file which contains an array of objects which have the values:
{
id: ..,
image: "require('./React.png')",
name: ...,
description:...,
technology:..,
},
The image value contains the file path of the image file I would like to use as a string. The image is in the same directory as my component and object file.
When I destructure the props I am able to pass the id, name, description, and technology values to my component and they are displayed on the app fine. When I place the image prop inside of the image source attribute within the image tag the image is not displayed. (I am using JSX)
I've tried passing the image prop like: {this.props.image}/{props.image} to no avail.
The last P tag contains the same image prop I am trying to pass to my image source and it displays the route to my file as a string: "require('./React.png')". So I know the prop is accessing the object value correctly. The image source attribute is just having a fit for some reason. Any help would be appreciated. Thanks.
const ProjectCard =({image, name, description, technolgy})=>{
return(
<div className='pa3 dib br2 ma2 bw2 shadow-5 grow tc'>
<img src={{image}} style={{width:"60px", height:"60px"}} alt='logo'/>
<div>
<h2>{name}</h2>
<p>{description}</p>
<p>{technolgy}</p>
<p>{image}</p>
</div>
</div>
Well, you literally wrote a string with the content "require('./React.png')", which means that will get passed down to your <img> component as src property. Since the string is not a valid URL, nothing will be displayed. Maybe your browser will display an error.
You have two options. Either you modify the string to be a correct URL by removing the require from the string; for example, you change it to "./React.png". But then you need to configure your backend to actually serve this image for you.
Option two is to import that image in your javascript code into a variable and pass that to the src property of your <img> tag.
For example like this:
import reactImage from './React.png';
const ProjectCard =({name, description, technolgy})=> (
<div className='pa3 dib br2 ma2 bw2 shadow-5 grow tc'>
<img src={{reactImage}} style={{width:"60px", height:"60px"}} alt='logo'/>
<div>
<h2>{name}</h2>
<p>{description}</p>
<p>{technolgy}</p>
<p>{image}</p>
</div>
</div>
);
But here is the catch. Since it looks like you are trying to display images dynamically, I would suggest you go with option 1 and NOT make images part of your bundle beforehand. Only do that with images that are a fixed part of your application, like icons or a logo.
Dynamic (content) images should be served from a web server.
Change value if the image in JSON to this:
{
...
image: require('./React.png'),
...
}
<img style={{ width: 300 }} src={ props.image } />

Resources