react-lightweight-router
Version:
A lightweight, type-safe routing solution for React applications with support for dynamic route parameters
68 lines (67 loc) • 1.79 kB
JavaScript
import { jsx as m } from "react/jsx-runtime";
import { createContext as d, useContext as f, useState as u, useEffect as p } from "react";
const h = d({
path: "/",
navigate: () => {
},
params: {},
setParams: () => {
}
}), R = ({ children: t }) => {
const [n, a] = u(
window.location.pathname + window.location.search
), [e, r] = u({});
p(() => {
const o = () => {
a(window.location.pathname + window.location.search);
};
return window.addEventListener("popstate", o), () => window.removeEventListener("popstate", o);
}, []);
const s = (o) => {
window.history.pushState({}, "", o), a(o);
};
return /* @__PURE__ */ m(h.Provider, { value: { path: n, navigate: s, params: e, setParams: r }, children: t });
}, i = () => f(h), C = () => {
const { params: t } = i();
return t;
};
function P(t, n) {
if (t === "*") return { isMatch: !0, params: {} };
const a = t.match(/:[^\/]+/g)?.map((c) => c.slice(1)) || [], e = t.replace(/:[^\/]+/g, "([^/]+)").replace(/\*/g, ".*"), r = new RegExp("^" + e + "$"), s = n.match(r);
if (!s)
return { isMatch: !1, params: {} };
const o = s.slice(1);
return { isMatch: !0, params: a.reduce((c, l, w) => (c[l] = o[w], c), {}) };
}
const E = ({
path: t,
element: n
}) => {
const { path: a, setParams: e } = i(), { isMatch: r, params: s } = P(t, a);
return p(() => {
r && e && e(s);
}, [r, s, e]), r ? n : null;
}, M = ({
to: t,
children: n
}) => {
const { navigate: a } = i();
return /* @__PURE__ */ m(
"a",
{
href: t,
onClick: (e) => {
e.preventDefault(), a(t);
},
children: n
}
);
};
export {
M as Link,
E as Route,
R as Router,
C as useParams,
i as useRouter
};
//# sourceMappingURL=react-lightweight-router.es.js.map