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 Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay