Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use useRef hook to scroll to a specific component?

I’m implementing a link in react and typescript that, after clicking, scrolls to the right component, I’m using useRef Hook.

But when I do that, the error occurs:

Type '{ ref: MutableRefObject<HTMLDivElement | null>; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'ref' does not exist on type 'IntrinsicAttributes'.

This is the code, what am I doing wrong? I’ve tried several ways

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  import NewComponent from '../NewComponent';

  const titleRef = useRef<null | HTMLDivElement>(null);

  const handleBackClick = (): any => {
    titleRef!.current!.scrollIntoView({ behavior: 'smooth' });
  };

return (
  <Container>
    <Link onClick={handleBackClick}>
      Button Text
    </Link>
     ...
     ...
     ...
     <SomeComponents />
     ...
     ...
     ...
     ...

   <NewComponent ref={titleRef} />
  </Container>
)

The NewComponent is a simple component, like:

const NewComponent = () => {
  
    return (
      <Container>
        // Its a simple component
      </Container>
    );
  };
  
  export default NewComponent;

Thanks to anyone who can help me with this

>Solution :

You would wanna use forwardRef to tell TypeScript that NewComponent can accept a ref that will hold a div element. Here is how you would do it as an example:

import { forwardRef } from "react";
const NewComponent = forwardRef<HTMLDivElement>((props, ref) => {
  return <div ref={ref}>{props.children}</div>;
});
import { useRef } from "react";
export default function App() {
  const titleRef = useRef<HTMLDivElement>(null);
  return (
    <div>
      <NewComponent ref={titleRef} />
    </div>
  );
}

I created this CodeSandbox if you wanna play with it. Also notice I change useRef<null | HTMLDivElement>(null) to useRef<HTMLDivElement>(null).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading