📜  react-router useNavigate - Javascript (1)

📅  最后修改于: 2023-12-03 14:46:59.803000             🧑  作者: Mango

React Router useNavigate

React Router is a popular library in the React ecosystem that enables routing between different components in a React application. The useNavigate hook is one of the new features introduced in React Router version 6 that allows programmatic navigation in a React application.

Installation

To use useNavigate, you first need to install React Router version 6. You can do this using your preferred package manager, such as npm or yarn.

Using npm
npm install react-router-dom@next
Using yarn
yarn add react-router-dom@next
Usage

Once you have installed React Router version 6, you can import and use the useNavigate hook in your React components.

import { useNavigate } from 'react-router-dom';

function MyComponent() {
  const navigate = useNavigate();

  const handleClick = () => {
    navigate('/path/to/route');
  };

  return <button onClick={handleClick}>Navigate</button>;
}

In the above example, we import the useNavigate hook from the react-router-dom package. We then use the useNavigate hook to get the navigate function, which allows us to programmatically navigate to a different route in our application.

We define a handleClick function that calls the navigate function with the desired path as an argument. This function is called when the user clicks on a button in the component, which will trigger the navigation.

Parameters

The navigate function returned by the useNavigate hook can take the following arguments:

Path

The first argument is a string representing the path to navigate to. This can be an absolute path, such as /path/to/route, or a relative path, such as ../relative/path/to/route.

navigate('/path/to/route');
State

The second argument is an optional object that represents the state associated with the new location. This can be used to pass data between different components in your application.

navigate('/path/to/route', { data: 'foo' });
Replace

The third argument is an optional boolean that determines whether the new location should replace the current location in the browser history or not. If set to true, the current location will be replaced instead of adding a new entry to the history.

navigate('/path/to/route', { replace: true });
Conclusion

The useNavigate hook in React Router version 6 allows programmatic navigation in a React application. It provides a simple and intuitive API that makes it easy to navigate between different components in your application. With the useNavigate hook, you can easily create dynamic and interactive user interfaces that respond to user interactions in real-time.