In the previous 5 section, we have created:
transform to browser-compatible JS with Babel install Webpack, transform JSX, SCSS, CSS (no need for stand-alone Babel) We could use create-react-app to do all those things
installed Webpack with Babel (no more babel or webpack config files) manifest.json which is allow our web app to become PWA (support for offline mode) serviceWorker.js - manage notification and offline
Server-side Routing vs Client-side Routing
React Router can be used more than just the web
Android, iOS app (native)
Learn more at
React v5
Install
npm i react-router-dom
npm install --save react-router-dom
Create-react-app does not come with Router installed
Import 2 components
BrowserRouter
Route
BrowserRouter component requires only 1 nested element inside
you have to add another DIV to add many routes inside
const routes = (
<BrowserRouter>
<div>
<Route path="/" component={AppIndex} exact={true} />
<Route path="/about" component={About} exact={true} />
</div>
</BrowserRouter>
)
we use exact={true} to force React to render correct components
Config devServer to only server index.js, not entire URL
because by default, the browser will render the URL from server side
devServer: {
historyApiFallback: false
}
So, the index.js file should render routes, not App
Setup 404
Import Switch
import { Route, Switch } from "react-router";
let routes = (
<Switch>
<Route exact path="/"><Home /></Route>
<Route path="/about"><About /></Route>
<Route path="/:user"><User /></Route>
<Route><NoMatch /></Route> // 404 here
</Switch>
);
Linking between Routes
If you add href link, the whole page will be reloaded you have to use <Link> router for linking
<a href="/">Home</a>
<Link to="/"></Link>
Header / Nav inside Router
Render body in components Render header inside routes
<NavLink to="/" activeClassName="is-active"></NavLink>
Organize Routes
AppRouter.js - export all react components Render AppRouter instead of app
Query String
hash - /about#anchor
path - /about
query - /about?query=abc
query - /about/:id
Connnected components can access via
props.match.params.id
props.match.params.pathname
props.match.params.hash
props.match.params.query