'useNavigate hook is not redirecting my page on authenticating with Azure AD in react.js
I am trying to navigate to dashboard page after successful login from Azure AD. However, only the address bar value is getting changed and the actual page is not coming.
Here is my code snippet.
import { useNavigate } from 'react-router-dom';
import { useMsal, useIsAuthenticated } from "@azure/msal-react";
const { instance } = useMsal();
const navigate = useNavigate()
const onSubmit = async () => {
try {
const response = await instance.loginPopup(loginRequest);
if(response){
navigate('dashboard/app')
}
} catch (error) {
console.error(error);
}
};
The address bar is only getting changed to 'dashboard/app' and the page is not coming.
I have tried by removing the async as well, however, it didn't work.
Any help on this please...
I need to navigate to the actual page.
Solution 1:[1]
The useNavigate hook (like all React hooks) can only be used inside a React component.
Without that there's no way to hook into the React lifecycle methods.
You also need to make sure that any component that this hook is attached to is a child of your BrowserRouter component since it needs that as a Provider to work.
i.e. if you have the following:
const App: () => (
<>
<AddressBar />
<BrowserRouter>
Pages and Routes and Stuff...
</BrowserRouter>
</>
)
And you try to call the useNavigate in your AddressBar component, it won't work.
Instead you've have to move the BrowserRouter up to surround the AddressBar component like this:
const App: () => (
<BrowserRouter>
<AddressBar />
<>Pages and Routes and Stuff...</>
</BrowserRouter>
)
You'll also need to make sure that the 'dashboard/app' route is valid.
Solution 2:[2]
Please check that the route 'dashboard/app' is valid and you are not missing the folder structure. And please make sure you are calling it from inside a react component like this: https://reach.tech/router/api/useNavigate
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Md Wahidul Azam |
