ref: https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf
react-router vs react-router-dom vs react-router-native
- React Router has been broken into three packages: react-router, react-router-dom, and react-router-native.
react-router-dom
- Router
-
BrowserRouter
: The<BrowserRouter>
should be used when you have a server that will handle dynamic requests . -
HashRouter
: while the<HashRouter>
should be used for static websites (where the server can only respond to requests for files that it knows about). History
- example: Router components only expect to receive a single child element.
import { BrowserRouter } from 'react-router-dom' ReactDOM.render(( <BrowserRouter> <App /> </BrowserRouter> ), document.getElementById('root'))
-
- Routes
-
<Route>
- path :which is a string that describes the pathname that the route matches.
- exact: match the route compeletely. (will be default true after v5).
- only match the pathname of location, don't care about the querystring.
- use
path-to-regexp
package to determine if a route element'spath
prop matches the current location. -
match
object: when the route's path matched, amatch
object will be created- url: the matched part of the current location's pathname.
- path: the route's path.
- isExact: path===pathname.
- params: an Object containing values from the
pathname
that were captured bypath-to-regexp
.
-
<Switch>
- to group
<Route>
- will iterate over its children elements and only render the first one that matches the current pathname.
- to group
- What does the <Route> render
-
component
: A react component, no extra props to pass to the component. -
render
: A function that returns a React element -
children
: A function than returns a React element, this will always be rendered , regardless of whether the route's path matches the current location.
<Switch> <Route path='/home' component={Home}/> <Route path='/about' render={(props) => { <About {...props}/> } }/> <Route path='/posts' children={(props) => { props.match ? <Posts {...props}/> : <EmptyCard {...props}/> }}/> </Switch>
-
- path params
- for a path in
<Route>
, we can define a path aspath='/post/:id'
, if we want to capture theid
of the post, we can usematch.params.id
, - note that the captured value is a string.
- for a path in
- Links
- React Router provides a
<Link>
component to so that we can navigate between pages, and at the same time , it's different with using anchor element, it will not reload the whole page.
<header> <nav> <ul> <li><Link to='/home'>Home</Link></li> <li><Link to='/about'>About</Link></li> <li><Link to='/post'>Posts</Link></li> </nav> </header>
- React Router provides a