skip to Main Content

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


  1. I think you should use navigate function to redirect to the dashboard page.
    modify the line

    return redirect('/dashboard');
    

    to

    navigate('/dashboard');
    
    Login or Signup to reply.
  2. you want to one add item useState and one navigate() routes

    add useState

    const =[formData ,setFormData] = useState()
    

    Change redirect(‘/dashboard’);

    navigate('/dashboard'); 
    
    Login or Signup to reply.
  3. Your error is

        const navigate = useNavigate();
    

    Change to

    const navigation = useNavigation();
    

    And then use

    navigation.navigate('dashboard');
    

    Reference: useNavigation

    Login or Signup to reply.
  4. I recreated this example from the sample code you provided above. And everything worked fine.

    My main.jsx file

    import React from 'react'
    import ReactDOM from 'react-dom/client'
    import { RouterProvider } from 'react-router'
    import { createBrowserRouter } from 'react-router-dom'
    import Home from './Home.jsx'
    import HeaderUnauthorized from './HeaderUnauthorized.jsx'
    import Login from './Login.jsx'
    import Register from './Register.jsx'
    import Dashboard from './Dashboard.jsx'
    import HeaderAuthorized from './HeaderAuthorized.jsx'
    
    const router = createBrowserRouter([
      {
        index: true,
        element: <Home />,
      },
      {
        path: '/',
        children: [
          {
            path: '/',
            element: <HeaderUnauthorized />,
            children: [
              {
                path: 'login',
                element: <Login />,
              },
              {
                path: 'register',
                element: <Register />,
              },
            ],
          },
          {
            element: <HeaderAuthorized />,
            children: [
              {
                path: 'dashboard',
                element: <Dashboard />,
              },
            ],
          },
        ],
      },
    ])
    
    ReactDOM.createRoot(document.getElementById('root')).render(
      <React.StrictMode>
        <RouterProvider router={router} />
      </React.StrictMode>
    )
    

    Home page

    enter image description here

    Login Page

    import { Navigate, useNavigate } from 'react-router'
    
    const Login = () => {
      // const user = { name: 1 }
      const user = null
      const navigate = useNavigate()
    
      if (user) return <Navigate to='/dashboard' />
    
      const handleLogin = async (e) => {
        e.preventDefault()
        try {
          navigate('/dashboard') // Try 3
        } catch (err) {
          console.log(err)
        }
      }
    ...
    

    enter image description here

    After Login

    enter image description here

    First, try deleting your node_modules & package-lock.json and then make sure your package is up to date.

    The version I tried on

    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router": "^6.14.1",
    "react-router-dom": "^6.14.1"
    

    I used Vite to create this project.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search