skip to Main Content

I need my <Error403 /> to be rendered when a url with the prefix "403?redirected_from=/" is passed, but instead my <Error404 /> is rendered. I think my 404 wildcard is being used instead, but I dont understand why.

For example, when "navigate(/403?redirected_from=${location.pathname});" is used, with location.pathname equal to /403?redirected_from=/thing1/thing2/2023-07-24/2023-07-30
the 404 page is rendered.

Routes.tsx:

export default function MyRoutes() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<NavMenu />}>
          <Route path="403?redirected_from=/*" element={<Error403 />} />
          <Route path="/" element={Dashboard />} />
          <Route path="*" element={<Error404 />} />
        </Route>
      </Routes>
    </Router>
  );
}

2

Answers


  1. Chosen as BEST ANSWER

    coworker was able to solve the issue, changing routes path from 403?redirected_from=/* to /403.


  2. To achieve the desired behavior, you need to modify your route setup. The path prop in Route doesn’t support query parameters, so you can’t directly use "403?redirected_from=/*" as a path. Instead, you should use a custom route component and handle the logic inside it. Here’s how you can do it:

    import { useLocation } from 'react-router-dom';
    
    function MyRoutes() {
      return (
        <Router>
          <Routes>
            <Route path="/" element={<NavMenu />}>
              <Route element={<MainContent />} />
            </Route>
          </Routes>
        </Router>
      );
    }
    
    function MainContent() {
      const location = useLocation();
      const queryParams = new URLSearchParams(location.search);
    
      // Check if the URL contains the "redirected_from" query parameter with value "/"
      if (queryParams.get('redirected_from') === '/') {
        return <Error403 />;
      } else {
        return (
          <>
            <Route path="/" element={<Dashboard />} />
            <Route path="*" element={<Error404 />} />
          </>
        );
      }
    }
    

    In this updated code, we use the useLocation hook from react-router-dom to get the current location and its query parameters. Then we check if the "redirected_from" query parameter is set to "/", and if so, we render the component. If not, we render the regular content, including the component for the root path and the component for any other unmatched paths.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search