{"id":16986024,"url":"https://github.com/chung-leong/array-router","last_synced_at":"2025-03-22T01:42:31.056Z","repository":{"id":63264287,"uuid":"559685946","full_name":"chung-leong/array-router","owner":"chung-leong","description":"Lightweight, minimalist router for React","archived":false,"fork":false,"pushed_at":"2023-02-05T00:59:27.000Z","size":409,"stargazers_count":0,"open_issues_count":2,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2024-10-14T02:36:38.593Z","etag":null,"topics":["react","router","routing"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chung-leong.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2022-10-30T21:26:29.000Z","updated_at":"2023-01-31T20:46:32.000Z","dependencies_parsed_at":"2023-02-18T20:45:41.746Z","dependency_job_id":null,"html_url":"https://github.com/chung-leong/array-router","commit_stats":{"total_commits":62,"total_committers":1,"mean_commits":62.0,"dds":0.0,"last_synced_commit":"214b8094ca58fbc30c60db4352cda5d38a1dc666"},"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chung-leong%2Farray-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chung-leong%2Farray-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chung-leong%2Farray-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chung-leong%2Farray-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chung-leong","download_url":"https://codeload.github.com/chung-leong/array-router/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244894310,"owners_count":20527669,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["react","router","routing"],"created_at":"2024-10-14T02:44:40.452Z","updated_at":"2025-03-22T01:42:31.016Z","avatar_url":"https://github.com/chung-leong.png","language":"JavaScript","readme":"# Array-router ![ci](https://img.shields.io/github/actions/workflow/status/chung-leong/array-router/node.js.yml?branch=main\u0026label=Node.js%20CI\u0026logo=github) ![nycrc config on GitHub](https://img.shields.io/nycrc/chung-leong/array-router)\n\nArray-route is a simple, light-weight library that helps you manage routes in your React application. It's designed for React 18 and above.\n\n\n## Installation\n\n```sh\nnpm install --save-dev array-router\n```\n\n## Syntax\n\nApp.js\n```js\nimport { useRouter } from 'array-router';\n/* ... */\nexport default function App() {\n  const provide = useRouter();\n  return (\n    \u003cdiv className=\"App\"\u003e\n      {provide((parts, query, { throw404 }) =\u003e {\n        try {\n          switch (parts[0]) {\n            case undefined:\n              return \u003cWelcomePage /\u003e\n            case 'categories':\n              return \u003cCategoryPage /\u003e\n            case 'forums':\n              return \u003cForumPage /\u003e\n            default:\n              throw404();\n          }\n        } catch (err) {\n          return \u003cErrorPage error={err} /\u003e\n        }\n      })}\n    \u003c/div\u003e\n  );\n}\n```\n\nCategoryPage.js\n```js\nexport default function CategoryPage() {\n  const [ parts, query ] = useRoute();\n  const categoryId = parts[1];\n  return (\n    /* ... */\n  );\n}\n```\n\n## Basic design\n\nArray-router does not actually provide any routing logic. Instead, it gives you an `Array` containing\n`pathname.split('/')` and an `Object` containing values from `searchParams`. You can then use them to build out\na routing scheme that suits the needs of your app.\n\nThe aforementioned array and object are\n\u003ca href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy\"\u003eJavaScript proxy\nobjects\u003c/a\u003e. Array-router tracks all actions you perform on them and takes appropriate actions based on this\ninformation. In the above example, Array-router knows that `App` reads the first item when it renders while\n`CategoryPage` reads the second. If the location changes from `/categories/1` to `/categories/2`, Array-router will\nask `CategoryPage` to rerender but not `App` since only `parts[1]` is different.\n\nMutation of `parts` or `query` will cause the location to change. For instance, `parts.push('product', 17)` would move\nyou from `/categories/1` to `/categories/1/product/17`. Conversely, `parts.pop()` would send you from `/categories/1`\nto `/categories` while `parts.splice(0)` would send you all the way back to the root level.\n\n## Override default push vs. replace behavior\n\nBy default, changes to `parts` trigger calls to\n[`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState) while changes to `query` \ntrigger calls to [`history.replaceState`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState). \nWhen both type of changes occur, `pushState` has precedence.\n\nYou can use [`replacing`](./doc/replacing.md) to indicate that changes to the path should trigger a `replaceState`\ninstead of the default `pushState`:\n\n```js\n  replacing(() =\u003e {\n    parts[0] = 'categories';\n    parts[1] = 17;\n  });\n```\n\nConversely, you can use [`pushing`](./doc/pushing.md) to force the use of `pushState` when query variables are changes:\n\n```js\n  pushing(() =\u003e query.search = evt.target.value);\n```\n\n## Changing route during rendering\n\nNormally, you would change `parts` or `query` inside event handlers. You can make changes while a component is \nrendering--if you must. To do so, you need to use [`replacing`](./doc/replacing.md):\n\n```js\nfunction ProjectPage() {\n  const [ parts, query, { replacing } ] = useRoute();\n  if (parts[1] === 'summary') {\n    // fix an outdated URL\n    replacing(() =\u003e parts[1] = 'overview');\n  }\n  /* ... */\n}\n```\n\n`replacing` will throw a [`RouteChangeInterruption`](./doc/RouteChangeInterruption.md) error. When the router\nreceives this error from its error boundary, the changes will get applied. The error boundary's subsequent \nattempt at reconstructing the component tree should then proceed without incident.\n\nThis behavior is applicable to consumers of `useRoute` only. At the root level, changes get applied immediately.\n\n## Error handling\n\nArray-router provides an [error boundary](https://reactjs.org/docs/error-boundaries.html) that redirect\nerrors to the root-level component (i.e. the one that calls `useRouter`). A captured error is rethrown the \nmoment your code attempts to access one of the proxies (`parts` or `query`) or when [`rethrow`](./doc/rethrow.md) \nis called.\n\n## Array proxy\n\nWorking with array elements is somewhat unintuitive. `parts[0]`, `parts[1]` don't tell us what they actually \nrepresent. This is why the library provides a way for you to reference array elements by name instead:\n\n```js\n  const route = arrayProxy(parts, {\n    screen: 0,\n    id: 1,\n  });\n  if (route.screen === 'products') {\n    if (route.id) {\n      return \u003cProductPage id={route.id} /\u003e;\n    } else {\n      return \u003cProductList /\u003e;\n    }\n  } else ...\n```\n\n`route.screen` in the example is mapped to `parts[0]` while `route.id` is mapped `parts[1]`. The mapping works for\nboth reading and writing. It works for deleting too: `delete route.screen;` is translated as `parts.splice(0)`\n(since removal of both the zeroth element and those coming after is the only way we can ensure that `parts[0]`\nwould yield `undefined`).\n\nSee the documentation of [arrayProxy](./doc/arrayProxy.md) for more sophisticated ways of mapping elements to\nproperties.\n\n## Usage in non-web environment\n\nThis library can be employed in a non-web environment. You need to provide the following functions for \nhandling URLs in the router options:\n\n* [`parseURL`](./parseURL.md)\n* [`createURL`](./createURL.md)\n* [`applyURL`](./applyURL.md) \u003csup\u003eoptional\u003c/sup\u003e\n\n## API Reference\n\n### Hooks\n\n* [`useLocation`](./doc/useLocation.md)\n* [`useRouter`](./doc/useRouter.md)\n* [`useRoute`](./doc/useRoute.md)\n* [`useSequentialRouter`](./doc/useSequentialRouter.md)\n\n### Router methods\n\n* [`detour`](./doc/detour.md)\n* [`isDetour`](./doc/isDetour.md)\n* [`pushing`](./doc/pushing.md)\n* [`replacing`](./doc/replacing.md)\n* [`rethrow`](./doc/rethrow.md)\n* [`throw404`](./doc/throw404.md)\n* [`trap`](./doc/trap.md)\n\n### Error objects\n\n* [`RouteChangeInterruption`](./doc/RouteChangeInterruption.md)\n* [`RouteChangePending`](./doc/RouteChangePending.md)\n* [`RouteError`](./doc/RouteError.md)\n\n## Compatibility\n\nArray-router makes use of\n[JavaScript proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). According\nto Mozilla, it is available in the following environment:\n\n![Proxy compatibility](./doc/img/proxy-compatibility.jpg)\n\nSince the functionality in question cannot be polyfilled, Array-router does not work in any version of Internet Explorer\nor Opera Mini.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchung-leong%2Farray-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchung-leong%2Farray-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchung-leong%2Farray-router/lists"}