UNPKG

react-lightweight-router

Version:

A lightweight, type-safe routing solution for React applications with support for dynamic route parameters

3 lines (2 loc) 1.67 kB
(function(e,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],u):(e=typeof globalThis<"u"?globalThis:e||self,u(e.LightweightRouter=e.LightweightRouter||{},e.React,e.React))})(this,function(e,u,c){"use strict";const p=c.createContext({path:"/",navigate:()=>{},params:{},setParams:()=>{}}),f=({children:t})=>{const[s,a]=c.useState(window.location.pathname+window.location.search),[n,r]=c.useState({});c.useEffect(()=>{const i=()=>{a(window.location.pathname+window.location.search)};return window.addEventListener("popstate",i),()=>window.removeEventListener("popstate",i)},[]);const o=i=>{window.history.pushState({},"",i),a(i)};return u.jsx(p.Provider,{value:{path:s,navigate:o,params:n,setParams:r},children:t})},h=()=>c.useContext(p),d=()=>{const{params:t}=h();return t};function w(t,s){if(t==="*")return{isMatch:!0,params:{}};const a=t.match(/:[^\/]+/g)?.map(m=>m.slice(1))||[],n=t.replace(/:[^\/]+/g,"([^/]+)").replace(/\*/g,".*"),r=new RegExp("^"+n+"$"),o=s.match(r);if(!o)return{isMatch:!1,params:{}};const i=o.slice(1);return{isMatch:!0,params:a.reduce((m,P,R)=>(m[P]=i[R],m),{})}}const l=({path:t,element:s})=>{const{path:a,setParams:n}=h(),{isMatch:r,params:o}=w(t,a);return c.useEffect(()=>{r&&n&&n(o)},[r,o,n]),r?s:null},g=({to:t,children:s})=>{const{navigate:a}=h();return u.jsx("a",{href:t,onClick:n=>{n.preventDefault(),a(t)},children:s})};e.Link=g,e.Route=l,e.Router=f,e.useParams=d,e.useRouter=h,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}); //# sourceMappingURL=react-lightweight-router.umd.js.map