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
It is able to set the path as optional if you’re using the newest react-router version (now is v6.14):
So the user will be direct to the same
Form
component either url includesid
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:and in the
<Form>
component:It’s very convenient to separate two components.
The
react-router@5
Route
component’spath
prop accepts path strings that path-to-regexp@^1.7.0 understands. You can mark a path segment as optional:The path can also take an array of paths, you could specify multiple paths you want to match with a single
Route
:*Note: order the paths from more specific to less specific.