forked from asyncapi/website
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add collapsing and custom hook
- Loading branch information
1 parent
6563388
commit a2d7dba
Showing
2 changed files
with
143 additions
and
25 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import { useEffect, useRef, useState } from "react"; | ||
|
||
/** | ||
* @description Custom hook to observe headings and set the current active heading | ||
* @example const { currActive } = useHeadingsObserver(); | ||
* @returns {object} currActive - current active heading | ||
*/ | ||
export function useHeadingsObserver() { | ||
const observer = useRef(null); | ||
const headingsRef = useRef([]); | ||
const [currActive, setCurrActive] = useState(null); | ||
|
||
useEffect(() => { | ||
const callback = (entries) => { | ||
entries.forEach(entry => { | ||
if (entry.isIntersecting) { | ||
setCurrActive(entry.target.id); | ||
} | ||
}) | ||
} | ||
|
||
// The heading in from top 20% of the viewport to top 30% of the viewport will be considered as active | ||
observer.current = new IntersectionObserver(callback, { | ||
rootMargin: '-20% 0px -70% 0px', | ||
}); | ||
|
||
headingsRef.current = document.querySelectorAll('h2, h3'); | ||
headingsRef.current.forEach(heading => { | ||
observer.current.observe(heading); | ||
}) | ||
|
||
return () => observer.current.disconnect(); | ||
}, []); | ||
|
||
return { currActive } | ||
} |