Created router

This commit is contained in:
Dmitriy Shishkov 2021-07-15 20:06:09 +05:00
parent 02453c8cf6
commit ebecd1a974
No known key found for this signature in database
GPG Key ID: 14358F96FCDD8060
4 changed files with 60 additions and 6 deletions

View File

@ -1,12 +1,24 @@
import { Route } from "@type/router";
import React from "react";
import Bookshelf from "../Bookshelf";
import { Bookshelf } from "../Bookshelf";
import { Router } from "../router";
import { Err404 } from "../router/404";
import { UploadForm } from "../UploadForm";
import styles from "./App.module.css";
export const App = () => (
<div className={styles.container}>
<UploadForm />
</div>
);
const routes: Route[] = [
{ Component: Bookshelf, path: "/list" },
{ Component: UploadForm, path: "/upload" },
];
export const App = () => {
return (
<div className={styles.container}>
<Router routes={routes} startPath="/list" DefaultComponent={Err404} />
</div>
);
};
export default App;

8
src/router/404.tsx Normal file
View File

@ -0,0 +1,8 @@
import React from "react";
export const Err404 = () => (
<>
<h1>Error 404</h1>
<h4>Path not found {window.location.pathname}</h4>
</>
);

30
src/router/index.tsx Normal file
View File

@ -0,0 +1,30 @@
import React from "react";
import { BASE_URL } from "../constants";
import { Route } from "@type/router";
import { Err404 } from "./404";
interface IRouterProps {
routes: Route[];
startPath?: string;
DefaultComponent?: React.FC;
}
export const Router = ({
routes,
startPath,
DefaultComponent,
}: IRouterProps) => {
const currPath = window.location.pathname;
if (startPath && currPath === "/")
window.location.href = BASE_URL + startPath;
for (const route of routes) {
if (currPath === route.path || currPath === route.path + "/")
return <route.Component />;
}
if (DefaultComponent) return <DefaultComponent />;
return <Err404 />;
};

4
src/type/router.ts Normal file
View File

@ -0,0 +1,4 @@
export interface Route {
path: string;
Component: React.FC;
}