React 10: Router
Docs
https://reactrouter.com/
Router: Problem Statement
We wanna build single page apps with ReactJS. What to do?
�> Use RouteJS: library for SPA with client-side routing made easy
�> A library that provides navigational components for React Developers to create single-page applications (SPAs) with dynamic, client-side routing.
Router: Basics
import { Route, RouterProvider, createBrowserRouter } from 'react-router-dom'; const appRouter = createBrowserRouter(createRoutesFromElements( <Route path="/" element={ <Root/> }></Route> ));
Router: Links
LinksReplace <a> tags with <Link> and <NavLink> components so the web browser does NOT reload the page
Difference between <Link> and <NavLink> ??
Adds styling attributes to the rendered element when it matches the current URL.
Router: Route w Param
Example 1 Param, i.e. /Articles/todayinbarcelona
App.js
<Route path="Articles/:title" element={ <Article /> } />
Article Component
import { useParams, Link } from 'react-router-dom'; const { title } = useParams() ...
Example 2 Params, i.e. /Articles/todayinbarcelona/weather
App.js
Article Component
Nested Routes
They render both the component AND the subcomponent
This ONLY renders Secret component
This renders MyIndexComponent alongside MyComponent on /somepath ("index" keyword)
MyIndexComponent.js must add to the returned JSX (import the element first)
This BOTH renders About and Secret components � path is /about/secret
Index Routes
An index route is a special type of nested route that renders on its parent's path using the index attribute.
???
Conditional Nav
useNavigate() hook
useNavigate() hookuseNavigate() hook: imperatively updates the browser location
Why?
allows you to respond immediately to user input without having to wait (think )
Last updated