Set up react-router

This commit is contained in:
Florian Schroedl
2024-01-23 16:49:59 +01:00
parent 43e30ae0b3
commit 7b42d17ff8

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect } from "react";
import React, { useState, useEffect, useContext } from "react";
import { LineChart, Line, CartesianGrid, XAxis, YAxis } from "recharts";
import { format, addDays } from "date-fns";
import { Dashboard } from "@/components/main/routes/Dashboard";
@@ -7,10 +7,68 @@ import {
persistStorage,
} from "@/components/main/lib/state";
import { mergeDeepRight } from "ramda";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import {
createBrowserRouter,
RouterProvider,
useNavigate,
useMatches,
} from "react-router-dom";
import * as reactRouter from "react-router-dom";
const STORAGE_KEY = "ecoplanet";
const routes = {
dashboard: {
id: "Dashboard",
path: "/",
},
options: {
id: "Options",
path: "/options",
},
};
const Navigation = function ({ router }) {
const navigate = useNavigate();
const matches = useMatches();
const onUpdateRoute = (routePath: string) => {
navigate(routePath);
};
const activeRouteId = matches[0]?.id;
return (
<nav>
<ul className="flex mb-4 space-x-3">
{/*
* Ideally we would not map over the routes object, as object items are sorted by the runtime,
* so they might not represent the data from the source code!
* But for this use-case this is enough.
*/}
{Object.entries(routes).map(([key, route]) => {
const id = route.id;
const className = id === activeRouteId ? "font-bold" : "";
return (
<li className={className}>
<button onClick={() => onUpdateRoute(route.path)}>{id}</button>
</li>
);
})}
</ul>
</nav>
);
};
const Base = function ({ children }) {
return (
<div className="flex flex-col grow items-center justify-center h-full w-full bg-muted">
<Navigation />
{children}
</div>
);
};
const App: React.FC = () => {
const [state, setState] = useState(loadStorageOrDefault);
@@ -24,22 +82,27 @@ const App: React.FC = () => {
const router = createBrowserRouter([
{
path: "/",
element: <Dashboard state={state} updateState={updateState} />,
...routes.dashboard,
element: (
<Base id="Dashboard">
<Dashboard state={state} updateState={updateState} />
</Base>
),
},
{
path: "/options",
element: <div>Hello world!</div>,
...routes.options,
element: (
<Base id="Dashboard">
<div>Hello world!</div>,
</Base>
),
},
]);
return (
<div className="fixed top-0 right-0 bottom-0 left-0 flex">
<main className="flex grow flex-col">
<nav className="flex p-3 border-b border-solid border-slate-300"></nav>
<div className="flex grow items-center justify-center h-full w-full bg-muted">
<RouterProvider router={router} />
</div>
<RouterProvider router={router} />
</main>
</div>
);