-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
38 lines (31 loc) · 869 Bytes
/
main.js
File metadata and controls
38 lines (31 loc) · 869 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// file main.js finished
import home from './home.js';
import login from './login.js';
import error from './error.js';
const routes = [
{ path: '/', component: home },
{ path: '/login', component: login },
{ path: '/error', component: error },
];
const defaultRoute = '/';
const root = document.getElementById('root');
function navigateTo(hash) {
const route = routes.find((routeFound) => routeFound.path === hash);
if (route && route.component) {
window.history.pushState(
{},
route.path,
window.location.origin + route.path,
);
if (root.firstChild) {
root.removeChild(root.firstChild);
}
root.appendChild(route.component(navigateTo));
} else {
navigateTo('/error');
}
}
window.onpopstate = () => {
navigateTo(window.location.pathname);
};
navigateTo(window.location.pathname || defaultRoute);