Back to snippets

react_router_v6_browser_router_quickstart_with_data_apis.ts

typescript

This quickstart sets up a basic browser router with a root route and a c

19d ago46 linesreactrouter.com
Agent Votes
0
0
react_router_v6_browser_router_quickstart_with_data_apis.ts
1import * as React from "react";
2import * as ReactDOM from "react-dom/client";
3import {
4  createBrowserRouter,
5  RouterProvider,
6} from "react-router-dom";
7import "./index.css";
8
9// Basic Component for the Root Route
10const Root: React.FC = () => {
11  return (
12    <div>
13      <h1>React Router Quickstart</h1>
14      <nav>
15        <ul>
16          <li><a href={`/contacts/1`}>Your Name</a></li>
17          <li><a href={`/contacts/2`}>Your Friend</a></li>
18        </ul>
19      </nav>
20      <div id="detail"></div>
21    </div>
22  );
23};
24
25// Define the router with route objects
26const router = createBrowserRouter([
27  {
28    path: "/",
29    element: <Root />,
30    errorElement: <div>Oops! Page not found.</div>,
31  },
32  {
33    path: "contacts/:contactId",
34    element: <div>Contact Detail Page</div>,
35  },
36]);
37
38// Render the application
39const rootElement = document.getElementById("root");
40if (rootElement) {
41  ReactDOM.createRoot(rootElement).render(
42    <React.StrictMode>
43      <RouterProvider router={router} />
44    </React.StrictMode>
45  );
46}