check if an element is in the viewport in react.js
check if an element is inside a
viewport
:-
sets the attribute on the element
ref
. -
use
intersectionobserver
the api to track whether elements intersect.
app.js
import {useeffect, useref, usestate, usememo} from 'react'; export default functionapp() { const ref1 = useref(null); const ref2 = useref(null); const isinviewport1 = useisinviewport(ref1); console.log('isinviewport1: ', isinviewport1); const isinviewport2 = useisinviewport(ref2); console.log('isinviewport2: ', isinviewport2); return ( <div><divref={ref1}>top div {isinviewport1 && '| in viewport ✅'}div><divstyle={{height: '155rem'}} /><divref={ref2}>bottom div {isinviewport2 && '| in viewport ✅'}div>div> ); } functionuseisinviewport(ref) { const [isintersecting, setisintersecting] = usestate(false); const observer = usememo( () =>newintersectionobserver(([entry]) =>setisintersecting(entry.isintersecting), ), [], ); useeffect(() => { observer.observe(ref.current); return() => { observer.disconnect(); }; }, [ref, observer]); return isintersecting; }
this example shows how to check if an element is in the viewport.
intersectionobserver
the api enables us to check if a given element intersects the document.
useisinviewport
the hook takes a ref object pointing to the element we want to track.
intersectionobserver
the constructor takes a function which is called with an array of entries.
entries are an array of target elements for all observers that become more or less visible than one of the intersection observer ratios.
each entry describes the degree to which a given element intersects the root element (the document).
we destructure the entries because our
intersectionobserver
only tracks a single element (the one we set ref to).
we call observe()
the method, passing it the element we want to track - observer.observe(ref.current)
.
every time an element enters or leaves the viewport, intersectionobserver()
the function we passed to the constructor is called and we update the state.
// 👇️ gets called every time element enters or leaves viewport
new intersectionobserver(([entry]) =>
setisintersecting(entry.isintersecting),
)
useisinviewport
the hook will return true
if the element we set the ref object to is in the viewport .
if the element is not in the viewport, the hook returns false.
请注意
, on the initial render,useisinviewport
the hook will return false , since that isusestate
the initial value we passed toconst [isintersecting, setisintersecting] = usestate(false);
.
if you want to track changes to the hook's return value, use useeffect
a hook and add that value to the hook's dependencies.
const isinviewport1 = useisinviewport(ref1);
console.log('isinviewport1: ', isinviewport1);
useeffect(() => {
// 👇️ listen for changes
console.log(isinviewport1);
}, [isinviewport1]);
for reprinting, please send an email to 1244347461@qq.com for approval. after obtaining the author's consent, kindly include the source as a link.
article url:
related articles
publish date:2025/03/07 views:161 category:react
-
要在 react 中按下 enter 键时获取输入的值: 在输入字段上设置 onkeydown 属性。 当用户按下一个键时,检查该键是否为 enter 。 从状态变量访问输入字段的值。 import {usestate} from react ; co
publish date:2025/03/06 views:154 category:react
-
要使用钩子清除 react 中的 timeout 或 interval: 使用 useeffect 钩子设置超时或间隔。 从 useeffect 钩子返回一个函数。 使用 cleartimeout() 或 clearinterval() 方法删除组件卸载时的超时。、 import
publish date:2025/03/06 views:113 category:react
-
在 react 中检查一个 prop 是否传递给了一个组件: 将 prop 与 undefined 进行比较。 如果 prop 等于 undefined ,则它不会传递给组件。 否则,它被传递给组件了。 const button = ( {withicon} ) = { if
encountered two children with the same key error in react
publish date:2025/03/06 views:61 category:react
-
当我们从 map() 方法返回的两个或多个元素具有相同的键属性时,会出现 react 错误 encountered two children with the same key 。 要解决该错误,需要为每个元素的 key prop 提供唯一值或使用 index
export multiple components from a file in react.js
publish date:2025/03/06 views:134 category:react
-
使用命名导出在 react 中导出多个组件,例如 export function a() {} 和 export function b() {} 。 可以使用命名导入导入导出的组件,如 import {a, b} from ./another-file 。 我们可以在单个文件中根据需
publish date:2025/03/06 views:111 category:react
-
当我们将不是函数的值传递给元素的 onclick 属性时,会出现错误 expected onclick listener to be a function 。 要解决该错误,请确保仅将函数传递给元素的 onclick 属性。 const app = () = { // ⛔️
publish date:2025/03/06 views:111 category:react
-
在 react typescript 中将函数作为 props 传递: 在组件的接口中定义函数属性的类型。 在父组件中定义函数。 将函数作为道具传递给子组件。 interface buttonprops { sum : ( a: number , b: number ) =
publish date:2025/03/06 views:143 category:react
-
要使用react.js 创建一个仅包含允许的数字的输入字段: 将输入字段的类型设置为文本。 添加一个删除所有非数字值的 onchange 事件处理程序。 将输入值保存在状态变量中。 import {usest
publish date:2025/03/06 views:136 category:react
-
出现component cannot be used as a jsx component的错误有多种原因: 返回 jsx 元素数组而不是单个元素。 从组件返回 jsx 元素或 null 以外的任何值。 具有过时版本的 react 类型。 下面是一个产生上