<Route> wrapper to handle param/query parsing
npm install react-router-parsed




This package provides a
parsing and error handling in an organized fashion.
After working with react-router 4 enough, I started to realize that I had a lot of duplicated code to parse my
URL params and query string within render methods and event handlers for my components. For instance:
``js
class EditDeviceView extends React.Component {
render() {
const {match: {params}} = this.props
const organizationId = parseInt(params.organizationId)
const deviceId = parseInt(params.deviceId)
return (
{({loading, data}) => (
)}
)
}
handleSubmit = () => {
// duplicated code:
const {match: {params}} = this.props
const organizationId = parseInt(params.organizationId)
const deviceId = parseInt(params.deviceId)
...
}
}
`
After awhile, I had had enough of this. While I could have moved the parsing logic to a function in the same file,
I realized everything would be easier if I parse the params and query outside of my component and pass in the
already-parsed values as props.
`sh`
npm install --save react-router react-router-parsed
`js`
import Route from 'react-router-parsed/Route'
import useRouteMatch from 'react-router-parsed/useRouteMatch'
If you need to parse any url parameters, add a paramParsers property andparams
consume the prop in your route component, render function, orchildren:
`js
import Route from 'react-router-parsed/Route'
const EditUserRoute = () => (
paramParsers={{ userId: parseInt }}
render={({ params: { userId }, ...props }) => (
)}
/>
)
`
`js
import useRouteMatch from 'react-router-parsed/useRouteMatch'
const EditUserRoute = () => {
const {
match,
params: { userId },
error,
} = useRouteMatch({
path: '/users/:userId',
paramParsers: { userId: parseInt },
})
if (!match) return null
if (error) return
return
}
`
For each property in paramParsers, the key is the url parameter name, and the
value is a function that takes the following arguments and returns the parsed
value.
- raw - the raw string value of the parameterparam
- - the key, or parameter nameinfo
- - a hash of additional info; right now, just {match}
If you need to parse location.search, add a queryParser property andquery
consume the prop in your route component, render function, orchildren:
`js
import qs from 'qs'
import Route from 'react-router-parsed/Route'
const EditUserRoute = () => (
queryParser={(search) => qs.parse(search.substring(1))}
render={({ query: { showMenu }, ...props }) => (
)}
/>
)
`
If any of your parsers throws errors, they will be collected and passed to an
(optional) renderErrors function:
`js
import Route from 'react-router-parsed/Route'
const EditUserRoute = () => (
paramParsers={{
userId: (userId) => {
const result = parseInt(userId)
if (!userId || !userId.trim() || !Number.isFinite(result)) {
throw new Error(invalid userId: ${userId})`
}
return result
},
}}
render={({ params: { userId }, ...props }) => (
)}
renderErrors={({ paramParseErrors }) => (
Invalid URL: {paramParseErrors.userId}
)}
/>
)
renderErrors will be called with the same props as render, plus:
- paramParseError - a compound Error from parsing params, if anyparamParseErrors
- - an object with Errors thrown by the correspondingparamParsers
queryParseError
- - the Error from queryParser, if anyerror
- - paramParseError || queryParseError
With the useRouteMatch hook, error paramParseError, paramParseErrors, queryParseError
are props of the returned object:
`jsinvalid userId: ${userId}
const EditUserRoute = (): React.Node | null => {
const {
match,
params: { userId },
paramParseErrors,
} = useRouteMatch({
path: '/users/:userId',
paramParsers: {
userId: (userId) => {
const result = parseInt(userId)
if (!userId || !userId.trim() || !Number.isFinite(result)) {
throw new Error()``
}
return result
},
},
})
if (paramParseErrors) {
return (
Invalid URL: {paramParseErrors.userId}
)
}
if (!match) return null
return
}