| 1 |
import React, { useEffect, useState } from "react"; |
| 2 |
import Route from "../inc/Route"; |
| 3 |
|
| 4 |
/** |
| 5 |
* Router for different menu content. |
| 6 |
* |
| 7 |
* Router children components should be Route components. Else those who are not will be ignored. |
| 8 |
* |
| 9 |
* If no route matches, the last route will be shown. It can be used as 404 page. |
| 10 |
* |
| 11 |
* @param {Object} props component properties |
| 12 |
* @param {Array<Route>} props.routes routes array |
| 13 |
* @param {string} props.currentRoutePath current route path |
| 14 |
*/ |
| 15 |
function Router({ routes, currentRoutePath }) { |
| 16 |
const [CurrentRouteContent, setCurrentRouteContent] = useState(null); |
| 17 |
|
| 18 |
/** |
| 19 |
* useEffect hook. |
| 20 |
*/ |
| 21 |
useEffect(() => { |
| 22 |
const currentRoute = routes.find(route => { |
| 23 |
return route.getPath() === currentRoutePath; |
| 24 |
}); |
| 25 |
|
| 26 |
if (currentRoute) { |
| 27 |
setCurrentRouteContent(currentRoute.getElement()); |
| 28 |
} else { |
| 29 |
const lastRoute = routes[routes.length - 1]; |
| 30 |
setCurrentRouteContent(lastRoute.getElement()); |
| 31 |
} |
| 32 |
}, [currentRoutePath, routes]); |
| 33 |
|
| 34 |
return ( |
| 35 |
<div |
| 36 |
className={"tableberg-router-content-wrapper"} |
| 37 |
data-route-path={currentRoutePath} |
| 38 |
key={currentRoutePath} |
| 39 |
> |
| 40 |
{CurrentRouteContent} |
| 41 |
</div> |
| 42 |
); |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* @module Router |
| 47 |
*/ |
| 48 |
export default Router; |
| 49 |
|