[React] Routing

Introduction

The Router Package will

  1. Parse URL /Path
  2. Read Config
  3. Render / Load appropriate JSX / Component

Setup

npm install --save react-router-dom

1
2
3
4
5
6
7
8
9
10
11
12
// App.js
import { BrowserRouter } from 'react-router-dom';

render() {
return(
<BrowserRouter>
<div className="App">
<App />
</div>
</BrowserRouter>
)
}

The attribute of the routing is also passed to the components in the props. But the props are not available in the nested components in route component.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Component.js
import { Route, Link } from 'react-router-dom';
import Posts from './Posts/Posts';
import NewPost from './NewPost/NewPost';
// To pass props into nested component props
import { withRouter } from 'react-router-dom';
// Custom styling activate link
import { NavLink } from 'react-router-dom';
// Let React only render one route at a time
import { Switch } from 'react-router-dom';

render () {
return(
<nav>
<ul>
<li><NavLink
to="/"
activeClassName="my-active"
activeStyle={{ // style the activated route
color; "yellow",
}}
exact>Home</NavLink></li>
<li><NavLink to={{
pathname: "/new-post", // Absolute path: append directly after the domain
// If use relative path: append after current path
pathname: this.props.match.url + '/new-post',
hash: "#submit",
search: "?quick-submit=true"

}}>New Post</NavLink></li>
</ul>
</nav>
<Switch>
<Route path="/" exact render={() => <h1>home</h1>}/> // path is a relative path in default, have to add exact
<Route path="/" exact component={Posts}/> // Load components
<Route path="/new-post" exact component={Posts}/> // Load components
</Switch>
)
}
// Making children components aware of routing props data
export default withRouter(post)
1
2
3
NavLink .my-active {
color: yellow,
}

Pass route parameters

1
2
3
4
5
6
7
8
9
// Routing component
<Route path = "posts/:id" exact component={FullPost} />
// Posts component
import { Link } from 'react-router-dom';
import { FullPost } from './FullPost/FullPost';

return (
<Link to={'/posts/' + post.id}>
</Link>)

Extract params from route

1
2
3
4
5
componentDidMount() {
if (this.props.match.params.id) {

}
}
1
2
3
4
5
onClickHandler = (id) => {
this.props.history.push({
pathname: "/" + id
});
}