Categories
React Answers

How to manually invoke Link with React Router v6?

Spread the love

Sometimes, we want to manually invoke Link with React Router v6.

In this article, we’ll look at how to manually invoke Link with React Router v6.

How to manually invoke Link with React Router v6?

To manually invoke Link with React Router v6, we can use the navigate function.

For instance, we write

import React, { useCallback } from "react";
import { useNavigate } from "react-router-dom";

export default function comp() {
  const navigate = useNavigate();
  const handleOnClick = useCallback(
    () => navigate("/example", { replace: true }),
    [navigate]
  );

  return (
    <button type="button" onClick={handleOnClick}>
      Go home
    </button>
  );
}

to create the handleOnClick function with the useCallback hook called with a function that calls navigate with the '/example' destination route.

replace is set to true to replace the existing entry in the browser history.

We get the navigate function from the useNavigate hook.

Then we set the onClick prop of the button to handleOnClick to call it to navigate to /example when we click on the button.

Conclusion

To manually invoke Link with React Router v6, we can use the navigate function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *