Esses dias precisei usar o custom hook useScroll() que tinha feito em um projeto JavaScript. Porém, esse novo projeto está todo em TypeScript. Ambos ReactJs.
Esse hook serve para rolar a página até a posição de algum elemento específico.
Esse foi o resultado. Qualquer sugestão de melhoria, manda pra nós!
useScroll.ts
import { useRef } from 'react'; export type UseScrollResult = [() => void, React.RefObject<HTMLDivElement>]; const useScroll = (): UseScrollResult => { const htmlElementRef = useRef<HTMLDivElement | null>(null); const executeScroll = () => { if (htmlElementRef && htmlElementRef.current) { const { offsetTop } = htmlElementRef.current; offsetTop && window.scrollTo(0, offsetTop - 32); } }; return [executeScroll, htmlElementRef]; }; export { useScroll };
SomeComponent.tsx
import { useScroll } from 'hooks/useScroll'; const [executeScroll, htmlElRef] = useScroll(); const someActionAndScroll = () => { //... executeScroll(); }; return ( <Container> <TargetContainer ref={htmlElRef} /> <Header /> <List /> <Button onClick={someActionAndScroll} /> </Container> )
O hook useScroll exporta uma função que executa o scroll [executeScroll]
até posição recebida pela referência que colocaremos no elemento alvo [htmlElRef]
.
Top comments (0)