Skip to content

Instantly share code, notes, and snippets.

@Dron007
Created November 8, 2019 14:27
Show Gist options
  • Save Dron007/3fe0d5a3c3c8496dbbf7628e674a0a88 to your computer and use it in GitHub Desktop.
Save Dron007/3fe0d5a3c3c8496dbbf7628e674a0a88 to your computer and use it in GitHub Desktop.
Use DRY for React routes
import { generatePath } from 'react-router'
/**
Example:
const RouteAdminPartners = makeRoute('/admin/partners/:partnerId?')
console.log(RouteAdminPartners.pattern)
> '/admin/partners/:partnerId?'
console.log(RouteAdminPartners({ partnerId: 123 }))
> '/admin/partners/123'
console.log(RouteAdminPartners.toUrl({ partnerId: 123 }))
> '/admin/partners/123'
console.log(RouteAdminPartners.toUrl())
> '/admin/partners'
*/
function makeRoute (pattern) {
const routeHandler = {
get: function(target, prop) {
if (prop === 'pattern') {
return target()
} else if (prop === 'toUrl') {
return function(paramsMap) {
return generatePath(pattern, arguments[0])
}
}
},
apply: function(target, thisArg, argumentsList) {
return generatePath(pattern, argumentsList[0])
}
}
return new Proxy(() => pattern, routeHandler)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment