PluginProbe
Tableberg – Simple Gutenberg Table Block / 1.1.5
Tableberg – Simple Gutenberg Table Block v1.1.5
1.1.5 1.1.4 1.1.3 1.1.2 1.1.1 1.1.0 1.0.5 1.0.4 1.0.3 1.0.2 1.0.1 trunk 0.0.2 0.2.1 0.3.2 0.3.3 0.4.1 0.5.0 0.5.1 0.5.2 0.5.3 0.5.4 0.5.5 0.5.6 0.5.7 All 42 releases
tableberg / admin / src / components / RouterProvider.jsx

RouterProvider.jsx in Tableberg – Simple Gutenberg Table Block 1.1.5, at admin/src/components/RouterProvider.jsx

76 lines 1.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import React, { useEffect, useMemo } from "react";
2 import Router from "./Router";
3 import routes from "../inc/routes";
4 import { generateRouteArray } from "../inc/Route";
5 import NoRouterComponentFoundError from "../inc/err/NoRouterComponentFoundError";
6
7 /**
8 * RouterProvider component.
9 *
10 * @param {Object} props component properties
11 * @param {Router} props.children router component
12 * @class
13 */
14 function RouterProvider({ children, currentRoutePath, setCurrentRoutePath }) {
15 const RouterChild = useMemo(() => {
16 const Component = children?.type === Router ? children.type : null;
17
18 if (Component === null) {
19 throw new NoRouterComponentFoundError();
20 }
21
22 return Component;
23 }, [currentRoutePath]);
24
25 const generatedRoutes = useMemo(() => {
26 return generateRouteArray(routes);
27 }, []);
28
29 /**
30 * Parse url and set route path.
31 */
32 const parseRouteFromUrl = () => {
33 const url = new URL(window.location.href);
34 const urlRoute = url.searchParams.get("route");
35
36 if (urlRoute) {
37 setCurrentRoutePath(urlRoute);
38 }
39 };
40
41 /**
42 * Hook to add event listener for popstate.
43 */
44 useEffect(() => {
45 window.addEventListener("popstate", parseRouteFromUrl);
46 }, []);
47
48 /**
49 * Parse url and set route path at startup.
50 */
51 useEffect(() => {
52 parseRouteFromUrl();
53 }, []);
54
55 /**
56 * Add route path to url.
57 */
58 useEffect(() => {
59 const url = new URL(window.location.href);
60 url.searchParams.set("route", currentRoutePath);
61 window.history.pushState(null, null, url.href);
62 }, [currentRoutePath]);
63
64 return (
65 <RouterChild
66 routes={generatedRoutes}
67 currentRoutePath={currentRoutePath}
68 />
69 );
70 }
71
72 /**
73 * @module RouterProvider
74 */
75 export default RouterProvider;
76