context.js
5 years ago
index.js
3 years ago
link.js
3 years ago
route.js
5 years ago
utils.js
5 years ago
route.js
26 lines
| 1 | import { RouterContext } from "./context"; |
| 2 | const { useContext } = wp.element; |
| 3 | import { match } from "path-to-regexp"; |
| 4 | let prev = ""; |
| 5 | |
| 6 | export function Route({ path, onRoute, children }) { |
| 7 | // Extract route from RouterContext |
| 8 | const { route } = useContext(RouterContext); |
| 9 | |
| 10 | const checkMatch = match(`${path}`); |
| 11 | const matched = checkMatch(`${route.hash.substr(1)}`); |
| 12 | |
| 13 | if (!matched) { |
| 14 | return null; |
| 15 | } |
| 16 | |
| 17 | if (onRoute) { |
| 18 | if (prev !== matched.path) { |
| 19 | onRoute(); |
| 20 | } |
| 21 | prev = matched.path; |
| 22 | } |
| 23 | |
| 24 | return <div>{wp.element.cloneElement(children, { route: matched })}</div>; |
| 25 | } |
| 26 |