import React, { ReactNode, useEffect, useState } from 'react'; import { History, Location } from 'history'; export type RouteProps = { path: string; element: ReactNode; }; type RouterProps = { history: History; children: React.ReactElement[]; }; export const Route: React.FC = ({ element }) => { return <>{element}; }; export const Router: React.FC = ({ history, children }) => { const [currentLocation, setCurrentLocation] = useState({ pathname: '/', state: null, key: '', search: '', hash: '', }); useEffect(() => { history.push('/'); const handleRouteChange = ({ location }: { location: Location }) => { setCurrentLocation(location); }; const unlisten = history.listen(handleRouteChange); return () => { unlisten(); }; }, [history]); const renderElement = () => { const routes = React.Children.toArray( children, ) as React.ReactElement[]; const route = routes.find((r) => r.props.path === currentLocation.pathname); if (route) { return route.props.element; } // Handle 404 page not found return
404 - Page Not Found
; }; return <>{renderElement()}; }; export default Router;