this is the dynamic url
../Assets/${product.code}/${image1}.png
Some product have images and some does not have one. Therefore if the URL is not valid, I want to return different JSX element. Is there any way to check the validity of the image URL path ?
CodePudding user response:
You can do by try/catch
if an error then returns a different JSX element.
setProductImageSrc() {
try{
const src = require(`../Assets/${product.code}/${image1}.png`)
this.setState({ src });
}
catch(err){
//Do whatever you want when the image failed to load here show return different JSX element
}
}
CodePudding user response:
Solution There is an attribute on the image tag called one rror, which can triggered a function when the image fails to load. So what you can do is when image fails to load either put different image i.e default image or different JSX element as your wish.
Example:
import {useState} from "react"
function App() {
const[iserror,Setiserror]=useState(false)
const errorFunc =()=>{
Setiserror(true)
}
return (
<div>
{!iserror?<img one rror={errorFunc} src="noimageurl" alt=""/>
:<div>This will show when image fails to load</div>
</div>
);
}
CodePudding user response:
use fetch
const url="your-url-here"
fetch(url)
.then(res=>{
// valid image
})
.catch(error => {
// Image not found, Handle it here
}