DEV Community

Cover image for Custom hook useScroll.tsx :: React TypeScript
Breno Novelli
Breno Novelli

Posted on • Edited on

Custom hook useScroll.tsx :: React TypeScript

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 }; 
Enter fullscreen mode Exit fullscreen mode

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> ) 
Enter fullscreen mode Exit fullscreen mode

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)