Reputation: 95
I have a React Component, and a JSON
which consists of image url, i pass the image url into image tag in my component through mapping function.
Here is a Example of my Code:
import imgDetails from "../data/ImageDetails";
class Example extends Component {
constructor(props) {
super(props);
this.state = {
imgContentLoad: false
}
}
imageHandleLoad() {
this.setState({
imgContentLoad: true
})
}
render() {
return ({
imgDetails.map((imgDetails) => {
return ( <
React.Fragment > {
(this.state.imgContentLoad &&
<
img src = {
imgDetails.imgURL
}
onLoad = {
this.imageHandleLoad.bind(this)
}
/>) || <
div > image is loading < /div>
} <
/React.Fragment>
)
}
)
}
Here i want to display the "image is loading" text to show until the image loads so i wrote the above image onload function code. but my problem is, "image is loading" is showing infinitely the image is not showing. what is wrong here?
Upvotes: 0
Views: 1507
Reputation: 11800
extract it to a new component that will listen to the onload
event and return the img
when its loaded
class ImageWithLoading extends React.Component {
state = { isLoaded: false }
componentDidMount() {
const image = new Image();
image.onload = () => this.setState({ isLoaded: true });
image.src = this.props.src;
}
render() {
const { src } = this.props;
const { isLoaded } = this.state;
return isLoaded
? <img src={src} />
: <div>Loading image...</div>
}
}
Then make the Example
component just a container that maps the data to the ImageWithLoading
component
const Example = () => imgDetails
.map(({ imgURL }) => <ImageWithLoading key={imgURL} src={imgURL} />);
Upvotes: 2