DEV Community

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

Posted on • Edited on

1 3

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].

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay