onError does not load the default image - React - reactjs

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

Related

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' />
)
}

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>
);
};

Checking to see if image to be used for background-image has loaded using new Image()?

I'm trying to trigger an onLoad event for #material-ui's <CardMedia/> component. By default, it loads the image in a div as a background-image. Although it does have an option for setting an img component - you can't define a custom img component, and it doesn't expose Img props either. It only takes a media src.
This has made it difficult (for me) to check for onLoad events on the image.
My first thought was to use new Image() to load an image and then re-use that image's src in the <CardMedia /> component. Is that valid code or am I just loading the same image twice?
For example,
https://codesandbox.io/s/cardmedia-onload-tuqru
Quick look:
...
const handleImageLoaded = () => setImgIsLoading(false);
useEffect(() => {
const image = new Image();
image.onload = handleImageLoaded;
image.src = src ? `/t/width=500/matte=none/scale/f${src}/scaled.jpg` : undefined;
setImg(image);
}, []);
return (
<div className={classes.root}>
<div className={classes.itemRoot}>
{imgIsLoading && <Skeleton variant="rect" className={classes.skeleton} />}
{!imgIsLoading && (
<img
src={img.src}
alt={alt}
/>
)}
</div>
</div>
);
...
I'd say it's valid since the same image URL will only load once no matter how many instances of an image object you have with the same URL.

I am trying to fetch data with Unsplash in React JS

I have done to set the code like this, but whenever i execute the code i recieve an error, how can i fix the error
import React from 'react';
const ImageList = props => {
const image = props.images.map((image) => {
return (
<div>
<img src={image.urls.regular} />
</div>
)
});
return <div>{image}</div>
};
export default ImageList;
The error i receive in the following :
Line 5: img elements must have an alt prop, either with meaningful text, or an empty string for decorative images jsx-a11y/alt-text
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
Compiling...
Compiled with warnings.
As ChrisR and tenor528 mentioned, it's self-explanatory. You need to add an alt attribute to your images. Ideally, your image tag should be like this:
<img src="linkToImage" alt="description of Image">
alt attribute useful for accessibility purposes. For example, when someone is using a screenreader, the alt text would be read. That's why ESLint is giving you a warning.
Also, it is mentioned in the error, how to solve it:
1- Either add a description.
2- Put empty string.
So, in your case, if you are not getting the description in the props, replace
<img src={image.urls.regular} />
with
<img src={image.urls.regular} alt="" />
While if you are getting the description, to simply put that in your alt tag like alt={image.description}.

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