Skip to content

Instantly share code, notes, and snippets.

@davidmfoley
Created December 6, 2018 17:18
Show Gist options
  • Save davidmfoley/3a6866851a9d455884a03c8bd35a50ab to your computer and use it in GitHub Desktop.
Save davidmfoley/3a6866851a9d455884a03c8bd35a50ab to your computer and use it in GitHub Desktop.
easy access to query params with react-router v4
// @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