I have a login form such below:
const Login = () => {
const { user } = useAuth();
const navigate = useNavigate();
if(user) return (<Navigate to="/dashboard"/>);
const handleLogin = async (e) => {
e.preventDefault();
try {
const login = await login(formData);
console.log('test 0');
if(login.success) {
console.log('test 1');
return redirect('/dashboard'); // Try 1
// return (<Navigate to="/dashboard"/>);// Try 2
// navigate('/dashboard') // Try 3
}
}
}
return (
<form onSubmit={handleLogin}>
<label for="email">Email:</label>
<input type="email" name="email" placeholder="Enter email" required onChange={e => setFormData({...formData, email: e.target.value})}/>
<label for="password">Password:</label>
<input type="password" name="password" placeholder="Enter password" required onChange={e => setFormData({...formData, password: e.target.value})}/>
<button type="submit">Login</button>
</form>
)
}
The test 1
is logged in the console, but why doesn’t it redirect to /dashboard
page?
I have also used the Form
component provided by react-router-dom
package by import { Form } from 'react-router-dom'
, but it doesn’t work either. How to fix this to handle the redirect mechanism?
Update:
Here is the route that I create:
const router = createBrowserRouter([
{
index: true,
element: <Home/>,
},
{
path: "/",
children: [
{
element: <HeaderUnauthorized/>,
children: [
{
path: "login",
element: <Login/>,
},
{
path: "register",
element: <Register/>,
},
]
},
{
element: <HeaderAuthorized/>,
children: [
{
path: "dashboard",
element: <Dashboard/>,
}
]
}
]
},
])
4
Answers
I think you should use
navigate
function to redirect to the dashboard page.modify the line
to
you want to one add item useState and one navigate() routes
add useState
Change redirect(‘/dashboard’);
Your error is
Change to
And then use
Reference: useNavigation
I recreated this example from the sample code you provided above. And everything worked fine.
My main.jsx file
Home page
Login Page
After Login
First, try deleting your
node_modules
&package-lock.json
and then make sure your package is up to date.The version I tried on
I used Vite to create this project.