In this post we will display images with snap-scrolling affect in reactjs. We will use picsum photos to get the images and fetch instead of axios.
Lets start by creating a file SnapScroll.js and call the fecth() in useEffect.
useEffect(() => {
const url = "https://picsum.photos/v2/list?page=2&limit=50";
fetch(url)
.then((res) => res.json())
.then((respo) => {
setData(respo);
});
setLoading(false);
}, [data]);
The response is now stored in data, it consist of 50 objects each of which contains
{"id":"1047", "author":"sergeebee", "width":3264, "height":2448, "url":"unsplash.com/photos/bIQiMWxX_WU", "download_url":"picsum.photos/id/1047/3264/2448" }
We will now map the data and display the image
<div className="container">
{data.map((d, index) => (
<div key={index} className="img-box">
<img src={d.download_url} alt={d.id} className="img" />
</div>
))}
</div>
Now let's come to main part - How to add snap scrolling to it. We will add it using scroll-snap-type property to the container class and assign it a value of y mandatory. We will add overflow-y : scroll and webkit-scrollbar property to hide the scrollbar.
.container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
height: 91vh;
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
.container::-webkit-scrollbar {
display: none;
}
.img-box {
scroll-snap-align: start;
padding: 20px;
}
The list of css properties that can be added in snap scroll can be checked from MDN. Few useful properties are scroll-snap-align, scroll-margin. The sandbox demo is added below :-