JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://unpkg.com/universal-router@5/universal-router.min.js"></script>
JavaScript
//import UniversalRouter from 'universal-router';
const routes = [
{
name: 'home',
path: '/',
action: () => '<h1>Home</h1>',
},
{
name: 'users',
path: '/users',
action: () => '<h1>Users</h1>',
},
{
name: 'user',
path: '/user/:username',
action: (context) =>
`<h1>User ${context.params.username}</h1>` +
`<p>action(context) {</p>` +
`<ul>` +
Object.keys(context).map(key => {
let value = context[key];
if (key === 'route') {
console.log(value);
value = Object.assign({}, value, {
parent: '<route>'
});
}
switch (key) {
case 'next':
return `<li>context.next()</li>`;
case 'router':
return `<li>context.router</li>`;
default:
return `<li>context.${key}: <pre>${
JSON.stringify(value, null, 2)
}</pre></li>`;
}
}).join('') +
`</ul>` +
`<p>}</p>`,
},
];
const router = new UniversalRouter(routes);
// set custom current url in jsfiddle
window.history.pushState(null, '', '/user/jhon');
router.resolve(window.location.pathname).then(html => {
document.body.innerHTML = html;
});