Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React TypeScript: useRef to Link

How to use useRef with Link

import {Link} from 'react-router-dom';
const myLink = useRef<Link>(null);
...
myLink.current.click()
...

<Link to={{pathname: '/terms'}} id='myLink' ref={myLink} />

the error I get is Property 'click' does not exist on type 'Link<any>'.ts(2339)

I'm currently using the below but i want to move to useRef

    const myLink = document.getElementById('myLink');
    if (myLink) myLink.click();
like image 364
Bill Avatar asked Sep 07 '25 10:09

Bill


1 Answers

As the typescript error says, Link component cannot be clicked as simply as anchor. There are two proposed solutions to this.

  1. Change Link to <a href="..."> and use HTMLAnchorElement type in the useRef.

  2. Or if you want to stay using Link component from react-router-dom, you can access the props of the link component.

if (myLink.current) {
    window.location.assign(myLink.current.props.to.toString()); // redirect to the to prop on Link component
}
like image 171
Kryštof Řeháček Avatar answered Sep 10 '25 02:09

Kryštof Řeháček