Implement a light weight Route component amd no need to load third party library. (Inital implemented in React 18)
import React from 'react';
import PropTypes from 'prop-types';
interface RouteProprs{
path:string,
children: React.ReactNode
}
const Route = (props.RouteProps) : Element|null => {
if(window.location.pathname === props.path)
return <>{props.children}</>
else
return null;
}
Route.prototype = {
path: PropTypes.string.required
}
export default Route
To test this we can implement 2 simple components, one being App.tsx and other Menu.tsx.
Menu.tsx
import React from 'react';
const Menu = () => {
return <>
<ol>
<li><a href="/component1-path> Component 1 </a></li>
<li><a href="/component2-path> Component 2 </a></li>
....
</ol>
</>;
}
export default Menu;
App.tsx
import React from 'react';
cosnt App = () => {
return <>
<div><a href="http://localhost:3003/"> Home </a><div>
<Route path="/">
<Menu></Menu>
</Route>
<Route path="/component1-path">
<Component1></Component1>
</Route>
<Route path="/component2-path">
<Component2></Component2>
</Route>
...
</div>
<>;
}
Index.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(
document.getElementId('root') as HTMLElement
);
root.render(
<App/>
);
