skip to Main Content

Is it possible to navigate to the same route, with or without an id?

I have a table and when the row is clicked the user is navigated with a user id (will populate form with data fetched via id)
I also have a button to navigate the user to same page but without an id (populates empty form)

<Route path={[`${ROUTES.form}/:id`]}>>
  <Form />
</Route>
const handleNavigateToForm = (data: any) => {
  history.push(`${ROUTES.Form}/${data.id}`);
};

const addNewFormOnClick = () => {
  history.push(`${ROUTES.Form}/`);
};

2

Answers


  1. It is able to set the path as optional if you’re using the newest react-router version (now is v6.14):

    <Route  
      path="/form/:id?"
      element={<Form />}
    />
    

    So the user will be direct to the same Form component either url includes id or not.

    Another way to reach the goal is to use Layout Routes to nest the routes. If you need some specific component display with <Form />, it’s worthy to try this:

    <Route 
      path="/form"
      element={<Form />}
    >
      <Route
        path=":id"
        element={<SomeSpecificComponent />}
      />
    </Route>
    

    and in the <Form> component:

    const Form = () => {
      return (
        // some other elements
        <Outlet /> // This will display <SomeSpecificComponent /> if the url path is /form/:id
        // some other elements
      )
    }
    

    It’s very convenient to separate two components.

    Login or Signup to reply.
  2. The react-router@5 Route component’s path prop accepts path strings that path-to-regexp@^1.7.0 understands. You can mark a path segment as optional:

    <Route path={`${ROUTES.form}/:id?`} component={Form} />
    

    The path can also take an array of paths, you could specify multiple paths you want to match with a single Route:

    <Route
      path={[`${ROUTES.form}/:id`, ROUTES.form]} // *
      component={Form}
    />
    

    *Note: order the paths from more specific to less specific.

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