Skip to content

Instantly share code, notes, and snippets.

@christianscott
Last active July 9, 2019 00:39
Show Gist options
  • Save christianscott/74d7780b9fecacee32cc7b332e18461f to your computer and use it in GitHub Desktop.
Save christianscott/74d7780b9fecacee32cc7b332e18461f to your computer and use it in GitHub Desktop.
Route with query params (react router v4)
import * as React from 'react';
import { Redirect, Route, RouteComponentProps } from 'react-router';
type RouteWithQueryParamsProps<R extends string, O extends string> = {
path: string;
params: readonly ({
name: R;
required: true;
} | {
name: O;
required?: false;
})[];
fallbackPath: string;
Component: React.ComponentType<Record<R, string> & Record<O, string | undefined> & RouteComponentProps<any>>;
};
export const RouteWithQueryParams = <R extends string, O extends string>(props: RouteWithQueryParamsProps<R, O>) => {
return (
<Route path={props.path}>
{(routeProps) => {
const params = new URLSearchParams(routeProps.location.search);
const requiredParams = {} as Record<R, string>;
const optionalParams = {} as Record<O, string | null>;
for (const param of props.params) {
const value = params.get(param.name);
if (param.required) {
if (value != null) {
requiredParams[param.name] = value;
} else {
return <Redirect to={props.fallbackPath}/>;
}
} else {
optionalParams[param.name] = value;
}
}
return <props.Component {...routeProps} {...requiredParams} {...optionalParams}/>;
}}
</Route>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment