Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using history with react-router-dom v6

Tags:

I use react-router-dom version 6 and when I use this.props.history.push('/UserDashboard') it does not work. I changed it to

const history = createBrowserHistory(); history.push('/UserDashboard') 

but I still have a problem that when i would like to redirect to /UserDashboard just the link change and the page still the first one??

any help??**

        handleSubmit(event){                      event.preventDefault();         const history = createBrowserHistory();         axios({           method: "POST",            url:"http://localhost:3001/users/login",            data:  this.state         }).then((response)=>{           console.log(response.data.user.admin)           if (response.data.success === true && response.data.user.admin === false){                               const history = createBrowserHistory();                   history.push({                    pathname:"/users",                    state:{                    Key : response.data.user }      });                                     }else if(response.statusCode === 401 ){             alert("Invalid username or password");            window.location.reload(false);           }         })       } 

my routes.js file:

    import React from 'react';     import { Navigate } from 'react-router-dom';     import DashboardLayout from './Pages/DashboardLayout';     import AccountView from './Pages/views/account/AccountView';     import CustomerListView from './Pages/views/customer/CustomerListView';     import DashboardView from './Pages/views/reports/DashboardView';     import ProductListView from './Pages/views/product/ProductListView';     import SettingsView from './Pages/views/settings/SettingsView';     import Home from './Pages/home';     import About from './Pages/About';     import Partners from './Pages/Partners';     import Services from './Pages/services';     import Login from './Pages/Login';     import RD from './Pages/RD';     import ContactUs from './Pages/contactus';     import Apply from './Pages/apply';     import PartnerShip from './Pages/partnership';     import News from './Pages/News';     const routes = [      {      path: 'users',      element: <DashboardLayout />,      children: [       { path: 'account', element: <AccountView /> },       { path: 'customers', element: <CustomerListView /> },       { path: 'dashboard', element: <DashboardView /> },       { path: 'products', element: <ProductListView /> },       { path: 'settings', element: <SettingsView /> }       ]      },     {     path: '/',     element: <Home />,     },     {     path: 'about',     element: <About />     },      {path: 'partners',      element: <Partners />,          },     {     path: 'services',     element: <Services />,          },     {     path: 'contactus',     element: <ContactUs />,          },     {     path: 'login',     element: <Login />,           },{     path: 'RD',     element: <RD />,          },     {     path: 'apply',     element: <Apply />,           },      {     path: 'partnership',     element: <PartnerShip />,           },      {     path: 'News',     element: <News />,           }     ];      export default routes; 
like image 890
zineb Avatar asked Aug 18 '20 15:08

zineb


People also ask

What is the alternative of useHistory in react?

In react router v. 6, useHistory doesn't exist anymore, instead we have a useNavigate hook. This useNavigate hook gives us a navigate object and function, and this navigate function can be executed to navigate somewhere else.

Does react router use history API?

React Router uses the history package, which builds on the browser history API to provide an interface to which we can use easily in React apps. location - (object) The current location. May have the following properties: pathname - (string) The path of the URL.


2 Answers

In react-router-dom v6, you need to use useNavigate rather than useHistory.

See example from https://reacttraining.com/blog/react-router-v6-pre/

import React from 'react'; import { useNavigate } from 'react-router-dom';  function App() {   let navigate = useNavigate();   let [error, setError] = React.useState(null);    async function handleSubmit(event) {     event.preventDefault();     let result = await submitForm(event.target);     if (result.error) {       setError(result.error);     } else {       navigate('success');     }   }    return (     <form onSubmit={handleSubmit}>       // ...     </form>   ); } 
like image 167
Luke Phillips Avatar answered Sep 21 '22 18:09

Luke Phillips


Based on react-router-dom source code, you may do something like this :

import { Router } from 'react-router-dom';  const CustomRouter = ({   basename,   children,   history, }) => {   const [state, setState] = React.useState({     action: history.action,     location: history.location,   });    React.useLayoutEffect(() => history.listen(setState), [history]);    return (     <Router       basename={basename}       children={children}       location={state.location}       navigationType={state.action}       navigator={history}     />   ); }; 

Then make your history come from outside :

import { createBrowserHistory } from 'history';  const history = createBrowserHistory();  <CustomRouter history={history}>  ... </CustomRouter> 
like image 27
Poyoman Avatar answered Sep 24 '22 18:09

Poyoman