Mastering React Router V6 Part 1 ~ The Must Learn Client Side Routing for React
--
When developing a React SPA application, multi-page routing is a necessary requirement. The currently most popular client-side routing library is React Router. React Router V6 introduces a breaking change but also brings useful features compared to its predecessor. Let’s discuss!
Table of Content
Part 1
- React router architecture
- Route Component
- Nested Route
- Path segment (dynamic params, query params, etc)
- Redirection
- Error handler
- Not found page
Part 2
- Lazy loading & bundle splitting
- Private route
- React router hooks overview
- Other features (scroll restoration, global navigation, etc)
- Data APIs (NEW)
a. loader
b. action
1. React Router Architecture
React Router V6 introduces a new feature called data APIs, which can only be enabled by using a new router wrapper. There are four router wrappers available:
For most websites, you only need to be concerned with createBrowserRouter
. Inside this router wrapper, you can pass a router object with the following structure:
const router = createBrowserRouter([
{
path: "/",
element: <Root />,
children: [
{
path: "team",
element: <Team />,
},
],
},
]);
However, many people coming from React Router v4 or v5 prefer to use a Route component instead of an object. React Router V6 introduces a function called createRoutesFromElements
to convert route components back to route objects. For example:
const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<Root />}>
<Route path="dashboard" element={<Dashboard />} />
</Route>
)
);