React Router v7.3 introduced an improved and more declarative way to define routes using the Data Router APIs like createBrowserRouter
. In this tutorial, weβll walk through setting up a simple routing system in a React project using these new APIs.
π Step-by-Step Setup
1. Install React Router
First, install the react-router-dom
package:
npm install react-router-dom
This gives us access to all the routing components and utilities, including createBrowserRouter
, RouterProvider
, and Outlet
.
2. Create Route Config in src/routes/index.tsx
Inside our src
directory, create a routes
folder. Then create an index.tsx
file. This will define our route structure using the Data Router approach.
// src/routes/index.tsx
import App from "@/App";
import Product from "@/pages/product";
import User from "@/pages/user";
import { createBrowserRouter } from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
Component: App,
children: [
{
path: "user",
Component: User,
},
{
path: "product",
Component: Product,
},
],
},
]);
export default router;
Hereβs whatβs happening:
createBrowserRouter()
creates the route tree.- The
App
component acts as the root layout (common UI like headers, navbars). - Nested routes (
user
,product
) will be rendered inside theApp
component using<Outlet />
.
3. Create the Root Layout: App.tsx
Our App
component will serve as the shell that hosts child routes.
// src/App.tsx
import { Outlet } from "react-router-dom";
function App() {
return (
<>
<h1 className="text-3xl font-bold underline">Hello world!</h1>
<Outlet />
</>
);
}
export default App;
The <Outlet />
is where child routes like /user
and /product
will be rendered.
4. Setup Main Entry Point: main.tsx
Now integrate the router into your React app by using RouterProvider
.
// src/main.tsx
import React from "react";
import ReactDOM from "react-dom/client";
import { RouterProvider } from "react-router-dom";
import router from "@/routes";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<RouterProvider router={router} />
</React.StrictMode>
);
Note: We no longer use <App />
directly here β the routing system will handle rendering components.
5. Create the Page Components
Create two new components in src/pages
:
Product.tsx
// src/pages/Product.tsx
function Product() {
return <div>Welcome to the Product Page!</div>;
}
export default Product;
User.tsx
// src/pages/User.tsx
function User() {
return <div>Welcome to the User Page!</div>;
}
export default User;
β Final File Structure
src/
β
βββ App.tsx
βββ main.tsx
βββ routes/
β βββ index.tsx
βββ pages/
β βββ Product.tsx
β βββ User.tsx
π Run and Test
Start our development server:
npm run dev
Visit:
http://localhost:5173/
β Sees the root layouthttp://localhost:5173/user
β LoadsUser
component insideApp
http://localhost:5173/product
β LoadsProduct
component insideApp
If you do not know how to initiate your first react app, please follow this post first.