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

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 :

Related

React reference local image with absolute path with react

I'm building a simple desktop app using tauri, with a rust backend and a react frontend.
I'm passing the absolute path to a local image (on my device) from the backend to the frontend, and trying to use that path to display the image, but every time, the image isn't loaded and the console looks for the image inside the app folder:
I tried different things but I haven't been able to find a way that works for me to make sure the path given is interpreted as an absolute path, do you have any solution to suggest?
I've just play around and found that ReactJS default doesn't allow us to import any resources outside our app's folder.
As I tried to import an img via an absolute path from C:/ on my device, React returned this error:
Module not found: Error: You attempted to import C:/Users/admin/Pictures/Screenshots/a.png which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
You can either move it inside src/, or add a symlink to it from project's node_modules/.
So the only way I've found so far is to load the image as a base64 string, there are 2 ways to achieve that:
Import img as a ES6 module
Use <img src={require(...) />
Notice: If you paste your absolute path of the img to browser's address bar then double click it, you can see the "full path" of the img file with the prefix file:///.
Please refer to my example code below:
import React from 'react';
import imgSrc from 'file://C:/Users/admin/Pictures/Screenshots/a.png';
export const Demo = () => {
return (
<div className='test-import-img-from-device'>
<img src={imgSrc} />
It worked
<br /><br />
<img src={require('file://C:/Users/admin/Pictures/Screenshots/a.png')} />
It also worked
<br /><br />
<img src={'C:/Users/admin/Pictures/Screenshots/a.png'} />
Not worked
<br /><br />
<img src={'file://C:/Users/admin/Pictures/Screenshots/a.png'} />
Also not worked
</div>
)
}
Result:
In your case, I think <img src={require('file://...') /> would solve your issue.
Hope this can help!

Alias inside require function in React

I want to use alias inside require function for dynamically load img src.
There is a list of image items in the component. So it's not possible to import and map all of them manually in src.
Whenever i am trying relative path, it's working.
<img src={require('../../assets/images/' + imageurl)} alt={title} />
But if i change this line to below one, it's breaking.
<img src={`require(#assets/images/${imageurl})`} alt={title} />
Note: I already setup my assets alias in the project.
Try this:
<img src={require(`#assets/images/${imageurl}`)} alt={title} />

React won't load images

I am building a react blog and my images won't load. It shows me this message in console - src\components\BlogPost\index.js
Line 21:11: Redundant alt attribute. Screen-readers already announce `img` tags as an image. You don’t need to use the words `image`, `photo,` or `picture` (or any specified custom words) in the alt prop jsx-a11y/img-redundant-alt.
My source:
const BlogPost = (props) => {
return(
<div className="blogPostContainer">
<Card>
<div className="blogHeader">
<span className="blogCategory">Featured</span>
<h1 className="postTitle">..</h1>
<span className="postedBy">..</span>
</div>
<div className="postimageContainer">
<img src={require('../../blogPostimages/memories-from.jpg')} alt="Post image" />
</div>
</Card>
</div> )
}
Please help. Thank you.
<img src="example" aria-hidden alt="Picture of me taking a photo of an image" />
add "aria-hidden "
Redundant alt attribute warning doesn't prevent image loading. It means there is a meaningless alt in your image. alt attribute is useful for accessibility and must describe the image if the download fails.
Use an accurate description for images or alt="" for backgrounds and decorations.
Loading errors probably are caused by imports errors. Check image path, name, and location.
Here an example of an image import.
import logo from '../static/logo.png';
export default function Navbar() {
return (
<img src={logo} alt='website logo' />
)
}

How to load local images in React through props?

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`} />

Why is my react-lazyload component not working?

Up until a few days ago, my implementation of LazyLoad was working perfectly, but now I can't seem to get it to work.
This is my component:
import React from 'react';
import LazyLoad from 'react-lazyload';
import './image.scss';
const Image = image => (
<LazyLoad height={200} offset={100} once>
<div
className="image-container"
orientation={image.orientation}>
<img
className="image"
src={image.url}
alt={image.alt}
/>
{'caption' in image &&
<div className="meta">
<p className="caption">{image.caption}</p>
<p className="order">{image.currentNumber}/{image.maxNumber}</p>
</div>
}
</div>
</LazyLoad>
)
export default Image
And in App.js it is called like this:
render() {
return (
<div className="wrapper">
<GalleryTop details={this.state.gallery_top} />
{this.state.images.map((image, index) => <Image key={index} {...image} /> )}
</div>
)
}
But it won't work! Here's the demo environment:
https://gifted-kare-1c0eba.netlify.com/
(Check Network tab in Inspector to see that images are all requested from initial load)
There's also a video here
Any idea about what I am doing wrong?
Thanks in advance,
Morten
I ran into similar issues with the npm package react-lazyload. For one, this package only allows one child per LazyLoad component, so you would have to rearrange your hierarchy to make it work. Secondly, I found some strange behaviors when loading images that were already set within the viewport. The documentation does list import {forceCheck} from 'react-lazyload'; combined with forceCheck(); as a means of manually checking the elements, but I found this inconvenient and insufficient for components that aren't rerendering.
I was able to obtain the exact same functionalities with an easier implementation from the alternative package react-lazy-load. Mind the hyphen. This package also requires node>0.14. More or less, it does the same thing. You can read their documentation here: react-lazy-load

Resources