Created
December 6, 2018 17:18
-
-
Save davidmfoley/3a6866851a9d455884a03c8bd35a50ab to your computer and use it in GitHub Desktop.
easy access to query params with react-router v4
This file contains hidden or 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
// @flow | |
import * as React from 'react'; | |
import queryString from 'query-string'; | |
import { withRouter } from 'react-router-dom'; | |
export default function withQuery(WrappedComponent: any): any { | |
function QueryWrapper (props: Props) { | |
const query = queryString.parse(props.location.search) || {}; | |
const pushQuery = (query) => { | |
const { pathname } = props.location; | |
props.history.push({ | |
pathname, | |
search: queryString.stringify(query) | |
}); | |
}; | |
const replaceQuery = (query) => { | |
const { pathname } = props.location; | |
props.history.replace({ | |
pathname, | |
search: queryString.stringify(query) | |
}); | |
}; | |
return ( | |
<WrappedComponent {...props} replaceQuery={replaceQuery} pushQuery={pushQuery} query={query} /> | |
); | |
} | |
return withRouter(QueryWrapper); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment