The setup of the intersection observer might look a bit unfamiliar, but it's pretty simple once you understand what's going on.įirst, we create a new instance of the IntersectionObserver class. Create the intersection observer and starting to observe with useEffect.Create a reference to a DOM node with useRef.Create a state variable indicating whether the section is visible or not with useState.You can read more about each of these hooks in the documentation, but in our code we're doing the following: If you want to understand what's happening, I've written a step-by-step guide below, that explains what happens.įirst, we call three built in React Hooks - useState, useRef and useEffect. If you're looking for a copy and paste solution - here you go. Here's the code for implementing our component: And since we're using React, we can write a nice reusable component that we can re-use across our application. We're not digging too deep into the other cool stuff you can do with intersection observers in this article though, we're just implementing a nice "fade in on entry"-feature. It gives us some positional data, as well as nice-to-have properties like isIntersecting, which tell us whether something is visible or not. Quickly summarized, however, an intersection observer accepts a DOM node, and calls a callback function whenever it enters (or exits) the viewport. If you want to dig deep, I suggest you read this MDN article on the subject. The IntersectionObserver API is a really powerful tool for tracking whether something is on-screen, either in part or in full. Wouldn't it be nice if an event was triggered when your content was visible? We're going to use the IntersectionObserver DOM API to implement that behavior. Looks cool right? Now, how cool would it be if we had this effect whenever we scroll a new content block into the viewport? We're also transitioning the visibility property from hidden to visible. We also specify an initial opacity of 0.īy transitioning these two properties, we'll get the effect we're after. Here, we use the transform property to initially move our container down 1/5th of the viewport (or 20 viewport height units). Enter fullscreen mode Exit fullscreen mode
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |