React Router DOM

Installation

npm install react-router-dom

Import

import xyz from "react-router-dom";

Primary components

  • routers: BrowserRouter, HashRouter
  • route matchers: Route, Switch
  • navigation / route chargers: Link, NavLink, Redirect

1. Routers

BrowserRouter uses regular URL paths
HashRouter stores the current location in the hash portion of the URL: http://example.com/#/your/page

Router is rendered at the root of your element hierarchy.

ReactDOM.render(
  
    
  ,
  document.getElementById("root")
);

2. Route matchers

When Switch is rendered:

  1. It searches through its children Route elements to find one whose path matches the current url
  2. When it finds one, it renders that Route and ignore all others
  3. If no matches, then render nothing (null)

Order of Route:
more specific (typically longer) before less specific

function App() {
  return (
    
{/* If the current URL is /about, this route is rendered while the rest are ignored */} {/* Note how these two routes are ordered. The more specific path="/contact/:id" comes before path="/contact" so that route will render when viewing an individual contact */} {/* If none of the previous routes render anything, this route acts as a fallback. Important: A route with path="/" will *always* match the URL because all URLs begin with a /. So that's why we put this one last of all */}
); }

3. Navigation

Link creates links ( in HTML).

Home
// Home

NavLink can style itself as "active" when its to prop matches the current location


  React


// When the URL is /react, this renders:
// React

// When it's something else:
// React

Redirect: force navigation



tbc


Reference link
https://reacttraining.com/react-router/

你可能感兴趣的:(React Router DOM)