How to use specific parameter when using route parameter?

Viewed 14

I have a scenario where my route path is specified as ":type" but the type could be either "music" or "video" as per the implementation (more type to come in future). Here I want to show 404 page if type is not "music"/"video".

I'm using react-router@v6

Is there a way to handle this situation?

2 Answers

react-router-dom@6 routes paths don't handle regular expressions like RRDv5 did. The component will need to read the type param and conditionally redirect to your 404 page.

Example:

const navigate = useNavigate();
const { type } = useParams();

useEffect(() => {
  if (!["music", "video", ....other types....].includes(type)) {
    navigate("/404page", { replace: true });
  }
}, [navigate, type]);
if (!["music", "video", ...other types ...].includes(type)) {
    return <Navigate to='/error/404' />
}
return (
    ... 
)

this works fine as well. almost similar but this way I can stop rendering the generic view part

Related