Routes in React Router
Routes are the most important part of a React Router application. Let's look at a piece of code from the last lesson:
const router = createBrowserRouter([
{
path: '/',
element: <div>Hello Router!</div>,
},
]);
So, the properties of the path
and element
objects that we passed to the function when creating the router are the properties of the Route
object. In fact, this object has many properties, they can be found in the official documentation. Later, we will need some of them:
interface RouteObject {
path?: string;
index?: boolean;
children?: React.ReactNode;
caseSensitive?: boolean;
id?: string;
loader?: LoaderFunction;
action?: ActionFunction;
element?: React.ReactNode | null;
Component?: React.ComponentType | null;
errorElement?: React.ReactNode | null;
ErrorBoundary?: React.ComponentType | null;
handle?: RouteObject["handle"];
shouldRevalidate?: ShouldRevalidateFunction;
lazy?: LazyRouteFunction<RouteObject>;
}
We could have used an alternative JSX style and written the properties as props for the Route component, then our piece of code would have looked like this:
const router = createBrowserRouter(
createRoutesFromElements(
<Route
path = '/'
element = {<div>Hello Router!</div>}
/>
)
);
And, of course, it would be necessary to add a couple more lines to the import:
import {
createRoutesFromElements,
createBrowserRouter,
RouterProvider,
Route,
} from 'react-router-dom';
Both styles given in the lesson are equivalent. We will stick to the first option in the future.
Take the app you created in the previous lessons. Try rewriting the piece of code for creating the router (comment out the old one for now) using the alternative JSX syntax given in the lesson. Make sure the app works.
Put all the old code back in place and remove the new one. Make sure the app works.