1
+ import { parse } from 'querystring'
1
2
import * as React from 'react'
2
3
import { ReactType } from 'react'
3
4
import DefaultRoute from 'react-router/Route'
@@ -15,42 +16,66 @@ function extractParams(names, params) {
15
16
return newProps
16
17
}
17
18
19
+ function extractQueryParams ( queryParamNames , queryString ) {
20
+ return extractParams ( queryParamNames , parse ( queryString . substr ( 1 ) ) )
21
+ }
22
+
18
23
export type Options = {
24
+ params ?: string | Array < string > ,
19
25
match ?: string
20
26
exactly ?: boolean
21
27
state ?: string | Array < string >
22
28
routeComponent ?: ReactType
23
29
routeProps ?: any
30
+ queryParams ?: string | Array < string >
24
31
}
25
32
26
33
/**
27
34
* HOC for extracting router params.
28
35
*
29
36
* Example:
30
37
*
31
- * ```
32
- * const ShowName = withParams('name', { match: '/user/:name'})(({name}) =>
38
+ * ```typescript
39
+ * const ShowName = withParams({params: 'name', match: '/user/:name'})(({name}) =>
33
40
* <span>{name}</span>
34
41
* )
35
42
* ```
43
+ *
44
+ * ```typescript
45
+ * const ShowIdAndName = withParams({params: ['id', 'name'], match: '/user/:id/:name'})(({id, name}) =>
46
+ * <span>{id}{name}</span>
47
+ * )
48
+ * ```
36
49
*/
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 => {
38
57
const displayName = wrapDisplayName ( WrappedComponent , 'withParams' )
39
58
40
- names = Array . isArray ( names ) ? names : [ names ]
59
+ paramsNames = Array . isArray ( paramsNames ) ? paramsNames : [ paramsNames ]
60
+ queryParams = Array . isArray ( queryParams ) ? queryParams : [ queryParams ]
61
+
41
62
if ( state ) {
42
63
state = Array . isArray ( state ) ? state : [ state ]
43
64
}
44
65
45
66
if ( match ) {
46
67
return setDisplayName ( displayName ) ( props =>
47
68
< 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
+ />
49
74
} />
50
75
)
51
76
}
52
77
53
78
return setDisplayName ( displayName ) (
54
- props => < WrappedComponent { ...props } { ...extractParams ( names , props . params ) } />
79
+ props => < WrappedComponent { ...props } { ...extractParams ( paramsNames , props . params ) } />
55
80
)
56
81
}
0 commit comments