Installation:
npm install react-router-dom --save
There are two types of routers: <Browser Router>, <Hash Router>.
The Browser Router is used for dynamic and the Hash Router is used for static websites.
As we are creating a dynamic website we are using < Browser Router >.
Route:
<Route> is main component in React router. It is responsible to render some UI when a locations matches to route’s path.
Route render methods:
We have three ways to render something:
We must use one of these props based on the requirement. Most of the time we use ‘component’ to render a component.
‘render’ is used for inline rendering. ‘children’ works like ‘render’ but here it render even it doesn’t match location.
See the below example:
import { BrowserRouter, Route } from 'react-router-dom';
render(
<Provider>
<BrowserRouter>
<div>
<Route exact path="/" component={Home} />
<Route path="/about-us” component={AboutUs} />
</div>
</BrowserRouter>
</Provider>,
document.querySelector('.body')
);
Why did I mension exact to only Home component ?
In react-router V4, if more than one path matches to location then it renders more than one component. Here ‘/’ also matched to ‘/about-us’.
So we need to use it accordingly
Route props:
history:
It manages session history in javascript
Properties and methods of history:
Location:
It represents the current app location.
Match:
It contain the information about route path matched the url.
With Router:
We can get history properties to a component using withRouter. We need to wrap the component with withRouter.
See the below example:
import React from ‘react’;
import { withRouter } from ‘react-router-dom’;
class AB extends React.Component {
render() {
return <div> ... </div>;
}
}
export default withRouter(AB);
Link:
<Link> provides the navigation between pages in application. It uses ‘to’ prop to describe the path.
Import { Link } from ‘react-router-dom’;
const () = > (
<div>
<Link to=’/home’>Home</Link
</div>
)
It can be string or location object(which contains: pathname, search, hash, state). When we give string it converts to location object.
<Link to={{ pathname: ’/home’ }}>Home</Link>