React Routings - abukhalil-LTUC-ASAC/amman-401d4 GitHub Wiki
Since the topics we will be going through relates to single page apps (SPA's), we will be discussing how routing solves many problems arising from having SPA's with little to no helpful way to redisplay a content without redoing steps from A -> Z
.
- BrowserRouter is coupled with backend servers to handle requests (dynamic requests).
- HashRouter is the simple version that is used for static websites (fixed requests).
As shown below, router starts on the ReacDOM.render
level, and can only house a single child so might as well start at the very top.
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>
), document.getElementById('root'));
And from there, the path is taken into consideration and renders any component conditionally using the <Route exact path='/' component={Home}/>
at any child level. This commonly paired with a <switch>
tag and having all <Route>
's inside. Import with import { Switch, Route } from 'react-router-dom'
params that comes from a <Route>
can be accessed using match.params.[var]
on the rendered component level. And Linking other pages is done easily with <li><Link to='/'>Home</Link></li>
but you might wonder why not use
You might have noticed it is not easy at all trying to pass states from child to parent, one way we discussed last time was using callbacks, another is using the more efficient but big library of redux.
The child of a wrapped component takes in the wrapper's state and props, while maintaining own states and renders itself effectively. Chaining components in a way could be explained to be similar to chaining functions, and eventually be called Higher-Order Components.
And finally, a trick can a parent use to share all props with it’s children is using React.Children to map all possible children, and clone valid children along with props property.