Routing in React
we learn about a library that helps in routing in React.
First you need to install npm install --save react-router-dom.
Now lets us know about <BrowserRouter>
It grabs history object in router and passes it down the Component Tree.
Now , understanding <Route path = “/products” Component = {Products}/>
This Route looks at current URL if it matches with
path = “/products” it will render this Component = {Products}
Switch
when to use :-
<div className = “content”>
<Route path = "/products" Component = {Products} /> <Route path = "/posts" Component = {Posts}/> <Route path = "/admin" Component = {Dashboard}/> <Route path = "/" Component = {Home}/></div>Here two paths matches when path is /products
path = "/products"
path = "/"
We can use “exact” and other solution is <Switch>
Note : Switch renders the first child which matches
Therefore,you should order the Route from most Specific ones to most Generic ones.
link
link prevent overhead and http request.
How this link prevent addition HTTP request ?
link have regular anchor onClick:fn() which is handler which prevent the default behaviour of anchor this will not send addition request instead update the URL.
<Link to=”/posts/2018/06">Posts</Link>
Route Props
history , location and match are the default props.
it will be automatically injected once the path matches.
Passing Props
Route Parameters
prefix that parameter with colon:
We can read the route parameter through match object
<Route path = “/products/:id” Component = {ProductDetails}/>
Optional Parameter
<Route path = "/posts/:year/:month" Component = {Posts}/><Route path = "/admin" Component = {Dashboard}/><Route path = "/" Component = {Home}/>
If you exclude month from URL when you click month ; you will see Home is rendered.
So How can we improve this ?
Answer is using Regular Expression
<Route path = “/posts/:year?/:month?” Component = {Posts}/>Query String Parameter
They can be find in the location Object under search.
You need to install it !
import queryString from 'query-string';const {sortBy} = queryString.parse(location.search);
Redirect
<Route path = "/not-found" Component = {NotFound}/><Route path = "/" exact Component = {Home}/><Redirect to ="/not-found"/>
If we type invalid URL it will redirect to set path.
It also has some other application ; Sometime you want to redirect resources from one URL to other URL.
<Redirect from = “/messages” to = “/post”/>Programmatic Navigation
when you look at history object you will find push and replace function.
push -> will add new address in the browser history.so u can click the back button to where you were.
replace -> will replace the current address so we won’t have history
Replace are mostly used in Login Pages.
Nested Routing (self )
Conclusion
Its an Important Concept on react.
I will write more on it once i again enough knowledge on it !.
Till Then happy learning !
