I'm trying to catch all undefined route on the client side in front-end. The front-end is pure Javascript . I've defined component (HTML document) Object with Class .
class SignIn {
render() {
return (
`<div class="form-group">
<label for="email">Email</label>
<input id="email" type="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input id="password" type="password" placeholder="Password">
</div>
<div class="form-group">
<input type="button" value="Signin">
</div>`
)
}
}
And the render object is:
Route({ render: Signin, exact: true, path: '/signin' });
// default route
Route({ render: PageNotFound, path: '/*' });
It's working without pageNotFound Route , but catching undefined routes causes all defined routes to disappear and a default route responding to all routes.
This is the route object
const rootDocument = document.querySelector('#root');
export function Route(props) {
const { render, path, exact } = props;
const component = new render();
if (exact && path !== '/*') {
if (path === url.pathname) {
rootDocument.innerHTML = component.render();
}
} else {
rootDocument.innerHTML = component.render();
}
}
NB: It's a Reacts concept but not React .
This actually solves it but I think there should be an elegant way of doing it.
const rootDocument = document.querySelector('#root');
const isContent = document.querySelector('#root');
const url = location;
const Router_url = {};
export function Route(props) {
const { path, exact } = props;
Router_url[path] = { render: props.render }; // add to path object
Object.keys(Router_url).find((el) => {
if (el === url.pathname && exact && el !== '/*') {
const { render } = Router_url[el];
const component = new render();
rootDocument.innerHTML = component.render();
} else if (el === '/*' && isContent.children.length === 0) {
const { render } = Router_url['/*'];
const component = new render();
setTimeout(() => {
rootDocument.innerHTML = component.render();
}, 500);
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.