preface

I recently found out that React-router-dom is available in version 6, so I decided to give it a try.

The installation

  npm i react-router-dom
Copy the code

My default is version 6.0.2

An error message was found when Switch introduced Ts. Procedure

change

1.Switch is replaced with Routes. 2.Route removes exact; 3. Use element attribute in Route, remove original Component and render; 4. Replace useHistory useNavigate;

Overall: more semantic, simpler to use.

use

App.tsx

import { BrowserRouter, Route, Routes } from "react-router-dom";
import { Home } from "./page/home";
import { Login } from "./page/login";
import { Page1 } from "./page/page1";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <h1>router6</h1>
        <Routes>
          <Route path={"/"} element={<Home />} ></Route>
          <Route path={"/login"} element={<Login />} ></Route>
          <Route path={"/page1/ * "}element={<Page1 />} ></Route>
          <Route path={"/404"} element={<div>404</div>} ></Route>
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;
Copy the code

home.tsx

import { Link } from "react-router-dom";
export const Home = () = > {
  return (
    <>
      <h2>Where to, buddy?</h2>
      <ul>
        <li>
          <Link to={"/login"} >login</Link>
        </li>
        <li>
          <Link to={"/page1"} >page1</Link>
        </li>
      </ul>
    </>
  );
};
Copy the code

Login. TSX (including use of useNavigate)

import { useNavigate } from "react-router-dom";

export const Login = () = > {
  const nav = useNavigate();

  const goHome = () = > {
    nav("/");
  };

  return (
    <>
      <button onClick={goHome}>go Home</button>
      <br />
      login
    </>
  );
};

Copy the code

Note: useNavigate() cannot be placed inside the goHome function

 const goHome = () = > {
    const nav = useNavigate();
    nav("/");
  };
Copy the code

Pag1.tsx (nested use)

import { Route, Routes } from "react-router-dom";

export const Page1 = () = > {
  return (
    <>
      <h3>page1</h3>
      <Routes>
        <Route path={"page1-1"} element={<>page1-1</>} ></Route>
        <Route path={"page1-2"} element={<>page1-2</>} ></Route>
      </Routes>
    </>
  );
};
Copy the code

These are some of the changes to the usage, and the new API:Outlet, but I don’t know what the use is.