DEV Community

zehra hindioğlu
zehra hindioğlu

Posted on

Using useNavigate in React Router

'useNavigate' is a hook provided by React Router, a popular library used for handling navigation in React applications. This hook allows you to programmatically navigate between different routes in your application.

How to Use useNavigate
1) Import the Hook: First, you need to import useNavigate from the react-router-dom package.

2) Create a Navigate Function: By calling useNavigate, you get a function that you can use to navigate to a different route.

3) Use the Function: Use this function whenever you want to change the route.

Example
In the provided example, we are using useNavigate to navigate to a specific application edit page after successfully creating or updating data.

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

const navigate = useNavigate();

onSuccess: (data) => {
let applicationId = data.data.apps.find(a => a.type === 'string').id;

navigate(`/apps/edit/${applicationId}`);
Enter fullscreen mode Exit fullscreen mode

}

Detailed Explanation
● Import the Hook: The useNavigate hook is imported from the react-router-dom package.
● Create the Navigate Function: const navigate = useNavigate(); creates a function called navigate that can be used to change the route.
● Use the Function in onSuccess: In the onSuccess callback, we find the apps ID where the type is 'string'. Then, we use the navigate function to go to the edit page for that apps.

Top comments (0)