Reputation: 1396
consider the following component in react:
import React from "react";
import { Carousel } from "react-bootstrap";
function CarouselHome() {
return (
<>
<Carousel fade pause="hover" id="carousel" variant="">
<Carousel.Item>
<img
className="d-block w-100"
src="https://source.unsplash.com/1280x400/?bali"
alt="First slide"
/>
<Carousel.Caption>
<p>Bali, Indonesia</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block w-100"
src="https://source.unsplash.com/1280x400/?maldives"
alt="Second slide"
/>
<Carousel.Caption>
<p>Maldives</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block w-100"
src="https://source.unsplash.com/1280x400/?greece"
alt="Third slide"
/>
<Carousel.Caption>
<p>Greece</p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</>
);
}
export default CarouselHome;
The source.unsplash.com returns an image, but it takes a second or so, thus the rest of the page loads before this component, I want to add a spinner while loading, how do I do this considering this is not even a fetch call?
Upvotes: 0
Views: 86
Reputation: 685
You can achieve that with this structure. Create <Image/>
and <Loader/>
component.
const Image = ({item}) => {
const [imageLoaded, setImageLoaded] = useState(false);
const handleImageLoad = () => {
setImageLoaded(true);
};
return (
<div>
{!imageLoaded && <Loader />}
<img src={item.src} alt={item.alt} onLoad={handleImageLoad} />
</div>
);
}
Upvotes: 0
Reputation: 954
You can apply logic something like this
import React, {useState} from "react";
import { Carousel } from "react-bootstrap";
function CarouselHome() {
const [imageLoaded, setImageLoaded]=React.useState(false);
return (
<>
<Carousel fade pause="hover" id="carousel" variant="">
<Carousel.Item>
<img
className={`w-100 ${
imageLoaded ? 'd-block' : 'd-none'
}`}
src="https://source.unsplash.com/1280x400/?bali"
alt="First slide"
onLoad={()=> setImageLoaded(true)}}
/>
{!imageLoaded && (
<div className="smooth-preloader">
</div>
)}
<Carousel.Caption>
<p>Bali, Indonesia</p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</>
);
}
export default CarouselHome;
i declared state variable with the name imageLoaded and changing this state on onLoad function of img and also changing the className based on state change
Upvotes: 1