i am making a react app if the src isn't valid i replace it with a default image now sometimes a image with a valid src doesn't load from the server cuz it's not found (404) i searched on internet and tried these:
<img one rror={this.src="https://image.defaul-img.jpg"} src={!imgURL ? "https://image.defaul-img.jpg" : imgURL} className="card-img-top" alt="..." />
and
<img src={!imgURL ? "https://image.defaul-img.jpg" : imgURL} className="card-img-top" alt="https://image.defaul-img.jpg" />
but none of them work what can i do
CodePudding user response:
You can use the try-catch statement in JavaScript to handle the error of a missing image file and display a default image. Here's an example in React:
import React from 'react';
import DefaultImage from './default-image.jpg';
class ImageComponent extends React.Component {
state = {
imageUrl: ''
};
componentDidMount() {
this.setImage();
}
setImage = () => {
try {
import(`./${this.props.imageName}.jpg`).then(({ default: imageUrl }) => {
this.setState({ imageUrl });
});
} catch (error) {
this.setState({ imageUrl: DefaultImage });
}
};
render() {
return <img src={this.state.imageUrl} alt="Image" />;
}
}
export default ImageComponent;
This code uses dynamic import to load the image file. If the image file is not found, the catch block will be executed and the default image will be used instead.
Incase you are using the latest react you can use the Hook API like this.
import React, { useState, useEffect } from 'react';
import DefaultImage from './default-image.jpg';
const ImageComponent = ({ imageName }) => {
const [imageUrl, setImageUrl] = useState('');
useEffect(() => {
setImage();
}, []);
const setImage = () => {
try {
import(`./${imageName}.jpg`).then(({ default: image }) => {
setImageUrl(image);
});
} catch (error) {
setImageUrl(DefaultImage);
}
};
return <img src={imageUrl} alt="Image" />;
};
export default ImageComponent;
CodePudding user response:
this code works i find it on stack overflow sorry i will not post a question before properly researching again
<img one rror={({ currentTarget }) => {
currentTarget.onerror = null; // prevents looping
currentTarget.src = "https://image.defaultimg.jpg";
}} src={!imgURL ? "https://image.defaultimg.jpg" : imgURL} className="card-img-top" alt="..." />
CodePudding user response:
Create a ref
for img
element and handle fallback
cases,
import { useRef } from "react";
import "./styles.css";
export default function App() {
return (
<div className="App">
<Image src="/me.png" fallback="https://source.unsplash.com/random" />
</div>
);
}
function Image({ src, fallback }) {
const ref = useRef();
function handleFallback() {
// Nullify the error event for subsequent calls
ref.current.onError = null;
ref.current.src = fallback;
}
return <img alt="My img" ref={ref} src={src} one rror={handleFallback} />;
}
For vanilla.js
version of the handling :How does one use the one rror attribute of an img element