React Router DOM
- A single-page application built with React uses routing to achieve page jumps.
- In React, the commonly used two packages can achieve this demand, that is,
react-router
andreact-router-dom
.
React Router DOM
- Based on
react-router
, some functions in the browser operating environment have been added.react-router-dom
depends onreact-router
.
npm install react-router-dom yarn add react-router-dom
Components in React Router
Router:
<BrowserRouter>
and
<HashRouter>
Route Matcher:
<Route>
and
<Switch>
Route Changer:
<Link>
,
<NavLink>
and
<Redirect>
Router
The Main Difference between is
<BrowserRouter>
and<HashRouter>
- How the way they store URLs and communicate with the webserver.
- To use a router, make sure to present it at the root of the element
import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter } from "react-router-dom"; const App = () => ( <h1>Hello World!!</h1> ); ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById("root") );
Route Matcher
When
<Switch>
renders, it will search its children<Route>
contents to find a path that matches the current URL.
import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter, Switch, Route } from "react-router-dom"; const Contact = () => <div>Contact US</div>; const App = () => ( <BrowserRouter> <Switch> <Route path="/contact" component={Contact}></Route> </Switch> </BrowserRouter> ); ReactDOM.render( <App />, document.getElementById('root') );
Route Changer
<Link>
component to create a link in the application.<Redirect>
use when forced navigation.<NavLink>
It is a special type<Link>
that will add style parameters.
<div> <Link to="/">Contact</Link> <NavLink to="/contact2" activeClassName="name"> React </NavLink> <Redirect to="/signup" /> </div>;