{"id":20617635,"url":"https://github.com/jcoreio/react-router-parsed","last_synced_at":"2025-04-15T11:29:59.991Z","repository":{"id":40748832,"uuid":"140627264","full_name":"jcoreio/react-router-parsed","owner":"jcoreio","description":"\u003cRoute\u003e wrapper to handle param/query parsing","archived":false,"fork":false,"pushed_at":"2023-11-10T21:11:48.000Z","size":3032,"stargazers_count":1,"open_issues_count":19,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-28T19:21:38.374Z","etag":null,"topics":["react","react-router"],"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/jcoreio.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-07-11T21:03:51.000Z","updated_at":"2023-11-10T21:09:07.000Z","dependencies_parsed_at":"2023-02-05T02:01:24.386Z","dependency_job_id":null,"html_url":"https://github.com/jcoreio/react-router-parsed","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Freact-router-parsed","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Freact-router-parsed/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Freact-router-parsed/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jcoreio%2Freact-router-parsed/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jcoreio","download_url":"https://codeload.github.com/jcoreio/react-router-parsed/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248647256,"owners_count":21139081,"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","react-router"],"created_at":"2024-11-16T12:05:08.442Z","updated_at":"2025-04-15T11:29:59.964Z","avatar_url":"https://github.com/jcoreio.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# react-router-parsed\n\n[![CircleCI](https://circleci.com/gh/jcoreio/react-router-parsed.svg?style=svg)](https://circleci.com/gh/jcoreio/react-router-parsed)\n[![Coverage Status](https://codecov.io/gh/jcoreio/react-router-parsed/branch/master/graph/badge.svg)](https://codecov.io/gh/jcoreio/react-router-parsed)\n[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)\n[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)\n[![npm version](https://badge.fury.io/js/react-router-parsed.svg)](https://badge.fury.io/js/react-router-parsed)\n\nThis package provides a \u003cRoute\u003e wrapper to handle url parameter and querystring\nparsing and error handling in an organized fashion.\n\n## Rationale\n\nAfter working with `react-router` 4 enough, I started to realize that I had a lot of duplicated code to parse my\nURL params and query string within render methods and event handlers for my components. For instance:\n\n```js\nclass EditDeviceView extends React.Component {\n  render() {\n    const {match: {params}} = this.props\n    const organizationId = parseInt(params.organizationId)\n    const deviceId = parseInt(params.deviceId)\n\n    return (\n      \u003cQuery variables={{organizationId, deviceId}}\u003e\n        {({loading, data}) =\u003e (\n          \u003cform onSubmit={this.handleSubmit}\u003e\n            ...\n          \u003c/form\u003e\n        )}\n      \u003c/Query\u003e\n    )\n  }\n  handleSubmit = () =\u003e {\n    // duplicated code:\n    const {match: {params}} = this.props\n    const organizationId = parseInt(params.organizationId)\n    const deviceId = parseInt(params.deviceId)\n\n    ...\n  }\n}\n```\n\nAfter awhile, I had had enough of this. While I could have moved the parsing logic to a function in the same file,\nI realized everything would be easier if I parse the params and query outside of my component and pass in the\nalready-parsed values as props.\n\n## Quick Start\n\n```sh\nnpm install --save react-router react-router-parsed\n```\n\n```js\nimport Route from 'react-router-parsed/Route'\nimport useRouteMatch from 'react-router-parsed/useRouteMatch'\n```\n\n### Parsing URL parameters\n\nIf you need to parse any url parameters, add a `paramParsers` property and\nconsume the `params` prop in your route `component`, `render` function, or\n`children`:\n\n```js\nimport Route from 'react-router-parsed/Route'\n\nconst EditUserRoute = () =\u003e (\n  \u003cRoute\n    path=\"/users/:userId\"\n    paramParsers={{ userId: parseInt }}\n    render={({ params: { userId }, ...props }) =\u003e (\n      \u003cEditUserView {...props} userId={userId} /\u003e\n    )}\n  /\u003e\n)\n```\n\n```js\nimport useRouteMatch from 'react-router-parsed/useRouteMatch'\n\nconst EditUserRoute = () =\u003e {\n  const {\n    match,\n    params: { userId },\n    error,\n  } = useRouteMatch({\n    path: '/users/:userId',\n    paramParsers: { userId: parseInt },\n  })\n\n  if (!match) return null\n  if (error) return \u003cErrorAlert\u003e{error.message}\u003c/ErrorAlert\u003e\n  return \u003cEditUserView match={match} userId={userId} /\u003e\n}\n```\n\nFor each property in `paramParsers`, the key is the url parameter name, and the\nvalue is a function that takes the following arguments and returns the parsed\nvalue.\n\n- `raw` - the raw string value of the parameter\n- `param` - the key, or parameter name\n- `info` - a hash of additional info; right now, just `{match}`\n\n### Parsing `location.search`\n\nIf you need to parse `location.search`, add a `queryParser` property and\nconsume the `query` prop in your route `component`, `render` function, or\n`children`:\n\n```js\nimport qs from 'qs'\nimport Route from 'react-router-parsed/Route'\n\nconst EditUserRoute = () =\u003e (\n  \u003cRoute\n    path=\"/\"\n    queryParser={(search) =\u003e qs.parse(search.substring(1))}\n    render={({ query: { showMenu }, ...props }) =\u003e (\n      \u003cApp {...props} showMenu={showMenu} /\u003e\n    )}\n  /\u003e\n)\n```\n\n### Error handling\n\nIf any of your parsers throws errors, they will be collected and passed to an\n(optional) `renderErrors` function:\n\n```js\nimport Route from 'react-router-parsed/Route'\n\nconst EditUserRoute = () =\u003e (\n  \u003cRoute\n    path=\"/users/:userId\"\n    paramParsers={{\n      userId: (userId) =\u003e {\n        const result = parseInt(userId)\n        if (!userId || !userId.trim() || !Number.isFinite(result)) {\n          throw new Error(`invalid userId: ${userId}`)\n        }\n        return result\n      },\n    }}\n    render={({ params: { userId }, ...props }) =\u003e (\n      \u003cEditUserView {...props} userId={userId} /\u003e\n    )}\n    renderErrors={({ paramParseErrors }) =\u003e (\n      \u003cdiv className=\"alert alert-danger\"\u003e\n        Invalid URL: {paramParseErrors.userId}\n      \u003c/div\u003e\n    )}\n  /\u003e\n)\n```\n\n`renderErrors` will be called with the same props as `render`, plus:\n\n- `paramParseError` - a compound `Error` from parsing params, if any\n- `paramParseErrors` - an object with `Error`s thrown by the corresponding\n  `paramParsers`\n- `queryParseError` - the `Error` from `queryParser`, if any\n- `error` - `paramParseError || queryParseError`\n\nWith the `useRouteMatch` hook, `error` `paramParseError`, `paramParseErrors`, `queryParseError`\nare props of the returned object:\n\n```js\nconst EditUserRoute = (): React.Node | null =\u003e {\n  const {\n    match,\n    params: { userId },\n    paramParseErrors,\n  } = useRouteMatch({\n    path: '/users/:userId',\n    paramParsers: {\n      userId: (userId) =\u003e {\n        const result = parseInt(userId)\n        if (!userId || !userId.trim() || !Number.isFinite(result)) {\n          throw new Error(`invalid userId: ${userId}`)\n        }\n        return result\n      },\n    },\n  })\n  if (paramParseErrors) {\n    return (\n      \u003cdiv className=\"alert alert-danger\"\u003e\n        Invalid URL: {paramParseErrors.userId}\n      \u003c/div\u003e\n    )\n  }\n  if (!match) return null\n  return \u003cEditUserView match={match} userId={userId} /\u003e\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjcoreio%2Freact-router-parsed","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjcoreio%2Freact-router-parsed","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjcoreio%2Freact-router-parsed/lists"}