Created
November 8, 2019 14:27
-
-
Save Dron007/3fe0d5a3c3c8496dbbf7628e674a0a88 to your computer and use it in GitHub Desktop.
Use DRY for React routes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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