skip to Main Content

I’m using React Router v5, and I wonder how can I match all children of /add but /add/.. in one path. For example /add_a ,/add, /add123 etc.

I’ve tried <Route path="/add*" element={<div>TEST</div>} />, but I got a warn that Route path "/add*" will be treated as if it were "/add/*".

<Routes>
 <Route path="/add*" element={<div>TEST</div>} />
</Routes>

reference:
https://v5.reactrouter.com/web/api/Route/path-string-string

2

Answers


  1. Try this /add[^/]+ this will match all but except the second "/"

    This means /add_somethinghere is matches
    enter image description here

    but /add_somethinghere/extrathing is not match
    enter image description here

    Try the playground here https://forbeslindesay.github.io/express-route-tester/

    Login or Signup to reply.
  2. You are actually using React-Router v6 according to the code and warning. React-Router v6 removed path regular expressions. You can read more about it in "What Happened to Regexp Routes Paths?".

    I suggest you use route path "/:add/*" and regular expression /^add.*$/ to:

    1. Assign the dynamic path segment to the add parameter
    2. Wildcard splat "*" to allow descendent route matching
    3. Use the regular expression to test that add parameter value in the routed component and conditionally redirect/render the specific content

    Example:

    import { useParams, useNavigate } from "react-router-dom";
    
    const TestComponent = () => {
      const navigate = useNavigate();
      const { add } = useParams();
    
      const match = add.match(/^add.*$/);
    
      useEffect(() => {
        if (!match) navigate(-1);
      }, [match]);
    
      return match ? <div>TEST</div> : null;
    };
    
    <Routes>
      ....
      <Route path="/:add/*" element={<TestComponent />} />
    </Routes>
    

    If you intended to use React-Router v5 then ensure you have the proper version installed:

    npm install react-router-dom@5
    

    And use the correct components and API:

    import { Switch, Route } from 'react-router-dom';
    
    ...
    
    <Switch>
      {/* more specific routes */}
      <Route path="/add*" component={TestComponent} />
      {/* less specific routes */}
    </Switch>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search