React Router - ita-social-projects/what-front GitHub Wiki
To install React Roter use:
npm install react-router-dom
- When you click
<Link>the router renders the matching<Route>.
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/counter">Counter</Link></li>
<li><Link to="/role-list">Role List</Link></li>
</ul>- A
<Switch>looks through its children<Route>s and renders the first one that matches the current URL.
<Switch>
<Route exact path="/" render={() => (<h1>Welcome to the WHAT project!</h1>)} />
<Route exact path="/counter" component={Counter} />
<Route exact path="/role-list" component={RoleList} />
<Route path="/role-list/:role" component={Role} />
<Route render={() => <h2>Page Not Found</h2>} />
</Switch>There are few hooks that let you access the state of the router and perform navigation from inside your components:
- useRouteMatch
- useParams
- useHistory
useRouteMatch hook attempts to match the current URL
const RoleList = () => {
const { url } = useRouteMatch();
return (
<div>
<ul>
<li><Link to={`${url}/secretary`}>Secretary</Link></li>
<li><Link to={`${url}/mentor`}>Mentor</Link></li>
<li><Link to={`${url}/student`}>Student</Link></li>
</ul>
</div>
);
};useParams returns an object of URL parameters. Use it to access match.params of the current .
const Role = () => {
const { role } = useParams();
return (
<div>
<h3>{role}</h3>
</div>
);
};useHistory hook gives you access to the history instance that you may use to navigate.
const Role = () => {
const history = useHistory();
return (
<div>
<button type="button" onClick={() => (history.push('/counter'))}>Counter</button>
<button type="button" onClick={history.goBack}>Go Back</button>
</div>
);
};