1+ import { parse } from 'querystring'
12import * as React from 'react'
23import { ReactType } from 'react'
34import DefaultRoute from 'react-router/Route'
@@ -15,42 +16,66 @@ function extractParams(names, params) {
1516 return newProps
1617}
1718
19+ function extractQueryParams ( queryParamNames , queryString ) {
20+ return extractParams ( queryParamNames , parse ( queryString . substr ( 1 ) ) )
21+ }
22+
1823export type Options = {
24+ params ?: string | Array < string > ,
1925 match ?: string
2026 exactly ?: boolean
2127 state ?: string | Array < string >
2228 routeComponent ?: ReactType
2329 routeProps ?: any
30+ queryParams ?: string | Array < string >
2431}
2532
2633/**
2734 * HOC for extracting router params.
2835 *
2936 * Example:
3037 *
31- * ```
32- * const ShowName = withParams('name', { match: '/user/:name'})(({name}) =>
38+ * ```typescript
39+ * const ShowName = withParams({params: 'name', match: '/user/:name'})(({name}) =>
3340 * <span>{name}</span>
3441 * )
3542 * ```
43+ *
44+ * ```typescript
45+ * const ShowIdAndName = withParams({params: ['id', 'name'], match: '/user/:id/:name'})(({id, name}) =>
46+ * <span>{id}{name}</span>
47+ * )
48+ * ```
3649 */
37- export const withParams = ( names , { match, exactly = true , state, routeComponent : Route = DefaultRoute , routeProps} : Options = { } ) => WrappedComponent => {
50+ export const withParams = (
51+ {
52+ params : paramsNames , match, exactly = true ,
53+ state, routeComponent : Route = DefaultRoute ,
54+ routeProps, queryParams,
55+ } : Options = { }
56+ ) => WrappedComponent => {
3857 const displayName = wrapDisplayName ( WrappedComponent , 'withParams' )
3958
40- names = Array . isArray ( names ) ? names : [ names ]
59+ paramsNames = Array . isArray ( paramsNames ) ? paramsNames : [ paramsNames ]
60+ queryParams = Array . isArray ( queryParams ) ? queryParams : [ queryParams ]
61+
4162 if ( state ) {
4263 state = Array . isArray ( state ) ? state : [ state ]
4364 }
4465
4566 if ( match ) {
4667 return setDisplayName ( displayName ) ( props =>
4768 < Route { ...routeProps } exact = { exactly } path = { match } render = { ( { match : { params} = { params : [ ] } , location} ) =>
48- < WrappedComponent { ...props } { ...extractParams ( names , params ) } { ...extractParams ( state , location . state ) } />
69+ < WrappedComponent { ...props }
70+ { ...extractParams ( paramsNames , params ) }
71+ { ...extractParams ( state , location . state ) }
72+ { ...extractQueryParams ( queryParams , location . search ) }
73+ />
4974 } />
5075 )
5176 }
5277
5378 return setDisplayName ( displayName ) (
54- props => < WrappedComponent { ...props } { ...extractParams ( names , props . params ) } />
79+ props => < WrappedComponent { ...props } { ...extractParams ( paramsNames , props . params ) } />
5580 )
5681}
0 commit comments