@@ -4,6 +4,7 @@ title: useOnScreen
44date : " 2018-11-08"
55gist : https://gist.github.com/gragland/d1175eb983772b077cb17ae0841c5329
66sandbox : https://codesandbox.io/s/y7kr0vll4v
7+ isMultilingual : true
78links :
89 - url : https://github.com/thebuilder/react-intersection-observer
910 name : react-intersection-observer
@@ -78,3 +79,67 @@ function useOnScreen(ref, rootMargin = "0px") {
7879 return isIntersecting;
7980}
8081```
82+
83+ ```typescript
84+ import { useState, useEffect, useRef } from "react";
85+
86+ // Usage
87+ function App() {
88+ // Ref for the element that we want to detect whether on screen
89+ const ref: any = useRef<HTMLDivElement>();
90+ // Call the hook passing in ref and root margin
91+ // In this case it would only be considered onScreen if more ...
92+ // ... than 300px of element is visible.
93+ const onScreen: boolean = useOnScreen(ref, "-300px");
94+
95+ return (
96+ <div>
97+ <div style={{ height: "100vh" }}>
98+ <h1>Scroll down to next section 👇</h1>
99+ </div>
100+ <div
101+ ref={ref}
102+ style={{
103+ height: "100vh",
104+ backgroundColor: onScreen ? "#23cebd" : "#efefef",
105+ }}
106+ >
107+ {onScreen ? (
108+ <div>
109+ <h1>Hey I' m on the screen < / h1>
110+ < img src= " https://i.giphy.com/media/ASd0Ukj0y3qMM/giphy.gif" / >
111+ < / div>
112+ ) : (
113+ < h1> Scroll down 300px from the top of this section 👇< / h1>
114+ )}
115+ < / div>
116+ < / div>
117+ );
118+ }
119+
120+ // Hook
121+ function useOnScreen (ref : any , rootMargin : string = " 0px" ): boolean {
122+ // State and setter for storing whether element is visible
123+ const [isIntersecting , setIntersecting ] = useState< boolean> (false );
124+
125+ useEffect (() => {
126+ const observer = new IntersectionObserver (
127+ ([entry ]) => {
128+ // Update our state when observer callback fires
129+ setIntersecting (entry .isIntersecting );
130+ },
131+ {
132+ rootMargin,
133+ }
134+ );
135+ if (ref .current ) {
136+ observer .observe (ref .current );
137+ }
138+ return () => {
139+ observer .unobserve (ref .current );
140+ };
141+ }, []); // Empty array ensures that effect is only run on mount and unmount
142+
143+ return isIntersecting;
144+ }
145+ ```
0 commit comments