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();
As the typescript error says, Link
component cannot be clicked as simply as anchor. There are two proposed solutions to this.
Change Link to <a href="...">
and use HTMLAnchorElement
type in the useRef
.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With