React Router Dom

SetUp (with Redux)

import React from "react";
import ReactDOM from "react-dom";
import * as serviceWorker from "./serviceWorker";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Dashboard from "./pages/dashboard";
import Index from "./pages";
import { Provider } from "react-redux";
import RoomApp from "./reducer";
import { createStore } from "redux";
const store: any = createStore(RoomApp, {});

ReactDOM.render(
<Provider store={store}>
  <Router>
    <div>
      <Switch>    
        <Route path="/dashboard" component={Dashboard} />
        <Route path="/" component={Index} />
      </Switch>
    </div>
   </Router>
  </Provider>,
  document.getElementById("root")
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

History and Location

Pure JS

  • for the navigating to new page and push it into history stack

<a
  href="/contact"
  onClick={(event) => {
    // stop the browser from changing the URL and requesting the new document
    event.preventDefault();
    // push an entry into the browser history stack and change the URL
    window.history.pushState({}, undefined, "/contact");
  }}
/>

// listen to the state change and change the content
window.addEventListener("popstate", () => {
  // URL changed!
});
  • we can obtain different info from window.location

window.location.pathname; // /getting-started/concepts/
window.location.hash; // #location
window.location.reload(); // force a refresh w/ the server
// and a lot more

Library

  • for navigation, we can simply use useNavigate and Link

// similar with a tag but without reloading the whole page as it is
// single page application
<Link to="/pins/123" state={{ fromDashboard: true }} />;

// trigger navigate directly
<Navigate to="/dashboard" replace={true} />

let navigate = useNavigate();
navigate("/users/123", { state: partialUser });

Matching

Setting Routes

<BrowserRouter>
    <Routes>
        <Route path="/" element={<Main/>}>
           <Route index element={<Test/>}/>
           <Route path="test1" element={<Test1/>}/>
        </Route>
        <Route path="/halo" element={<Halo/>}/>
        <Route path="*" element={<Error/>}/>
        <Route element={<PageLayout />}>
          <Route path="/tos" element={<Tos />} />
        </Route>
    </Routes>
 </BrowserRouter> 
 
 
 // url: / => <Main><Test/></Main>
 // url /test1 => <Main><Test1/></Main>
 // url: /halo => <Halo/> 
 // url: /tos => <PageLayout><Tos/></PageLayout>
 // other url => <Error/> 
import React from 'react'
import { Outlet } from 'react-router-dom'

const Main = () => {
  return (
    <>
      <div>Main Page</div>
       // Outlet can be test or test1 
      <Outlet/> 
    </>
  )
}


export default Main

Routes Ranking

From low to high
 1 "/",
 2 "/teams",
 3 "/teams/:teamId",
 4 "/teams/new"
<Route path="/" element={<Main/>}>
   <Route index element={<Test/>}/>
   <Route path="test1" element={<Test1/>}/>
</Route>
<Route path="/halo" element={<Halo/>}/>
<Route path="/halo/1" element={<Halo1/>}/>
  • On Main or Halo component, can write something like this, as the path is inherited, no need to enter the full relative path

<Link to="1" />
<Link to="test1" />

Last updated

Was this helpful?