Created router
This commit is contained in:
parent
02453c8cf6
commit
ebecd1a974
@ -1,12 +1,24 @@
|
|||||||
|
import { Route } from "@type/router";
|
||||||
import React from "react";
|
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 { UploadForm } from "../UploadForm";
|
||||||
|
|
||||||
import styles from "./App.module.css";
|
import styles from "./App.module.css";
|
||||||
|
|
||||||
export const App = () => (
|
const routes: Route[] = [
|
||||||
<div className={styles.container}>
|
{ Component: Bookshelf, path: "/list" },
|
||||||
<UploadForm />
|
{ Component: UploadForm, path: "/upload" },
|
||||||
</div>
|
];
|
||||||
);
|
|
||||||
|
export const App = () => {
|
||||||
|
return (
|
||||||
|
<div className={styles.container}>
|
||||||
|
<Router routes={routes} startPath="/list" DefaultComponent={Err404} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export default App;
|
export default App;
|
||||||
|
8
src/router/404.tsx
Normal file
8
src/router/404.tsx
Normal 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
30
src/router/index.tsx
Normal 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
4
src/type/router.ts
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
export interface Route {
|
||||||
|
path: string;
|
||||||
|
Component: React.FC;
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user