in react-router v5, I was able to specify a certain set of dynamic path properties in the following way: '/some-path/:someDynamicProperty(value1|value2|value3)' thus the only existing options for this path would be:
any other path(like /some-path/value1124) would be treated as an unknown path and caught by a * path
are there any alternatives in react-router v6?
I've checked the documentation, but actually found nothing about that
React-Router v6 removed path regular expressions. You can read more about it in "What Happened to Regexp Routes Paths?".
If you would like to limit the routes that are matchable then you've a couple options.
Explicitly render the routes you want to render. You can map an array of the dynamic path segment values to discrete routes.
<Routes>
....
{["value1", "value2", "value3"].map((someDynamicProperty) => (
<Route
key={someDynamicProperty}
path={generatePath("/some-path/:someDynamicProperty", {
someDynamicProperty
})}
element={<MyComponent />}
/>
))}
...
<Route path="/404" element={<NotFound />} />
<Route path="*" element={<Navigate to="/404" replace />} />
</Routes>
const MyComponent = () => {
const match = useMatch("/some-path/:someDynamicProperty");
// match?.params.someDynamicProperty -> "value1" | "value2" | "value3"
return (
....
);
};
Use a dynamic path segment that matches anything and perform the check in the component, redirecting if it is not a valid path segment.
<Routes>
<Route
path="/some-segment/:someDynamicProperty"
element={<MyComponent />}
/>
<Route path="/404" element={<NotFound />} />
<Route path="*" element={<Navigate to="/404" replace />} />
</Routes>
const MyComponent = () => {
const { someDynamicProperty } = useParams();
const match = /(value1|value2|value3)/.test(someDynamicProperty);
if (!match) return <Navigate to="/404" replace />;
return (
....
);
};