Home > Software design >  React Router conditional redirect
React Router conditional redirect

Time:07-29

I'm building a search UI using React, React Router and the awesome Edit react-router-conditional-redirect

react-router-dom@5

The useSearchParams hook doesn't exist in v5 so you can create your own.

import { useMemo } from 'react';
import { useLocation } from 'react-router-dom';

const useSearchParams = () => {
  const { search } = useLocation();
  const searchParams = useMemo(() => new URLSearchParams(search), [search]);
  return [searchParams];
};

Using a Wrapper

import useSearchParams from '../path/to/useSearchParams';

const QuaryParametersWrapper = ({ children, parameters = [] }) => {
  const [searchParams] = useSearchParams();

  const hasParameter = parameters.some(
    (parameter) => !!searchParams.get(parameter)
  );

  return hasParameter ? children : <Redirect to="/" />;
};

...

<Route
  path="/search1"
  render={(routeProps) => (
    <QuaryParametersWrapper parameters={["q"]}>
      <ReactiveList {...routeProps} />
    </QuaryParametersWrapper>
  )}
/>

Using a custom HOC

import { Redirect } from 'react-router-dom';
import useSearchParams from '../path/to/useSearchParams';

const withQueryParameters = (...parameters) => (Component) => (props) => {
  const [searchParams] = useSearchParams();

  const hasParameter = parameters.some(
    (parameter) => !!searchParams.get(parameter)
  );

  return hasParameter ? <Component {...props} /> : <Redirect to="/" />;
};

...

export default withQueryParameters("q")(ReactiveList);

...

import ReactiveListWrapper from '../path/to/ReactiveList';

...

<Route path="/search2" component={QueryReactiveList} />

Demo

Edit react-router-conditional-redirect (RRDv5)

  • Related