Home > Mobile >  React-Router - Redirect if URL parameter not passed
React-Router - Redirect if URL parameter not passed

Time:11-30

I want the redirect back to home if the params are not passed with the url. How can I achieve this? I tried something like this, but it`s not working:

export default function Summary() {
  const { id } = useParams();
  const navigate = useNavigate();
  if (!id) {
    navigate("/home");
  }

Thanks in advance

CodePudding user response:

add useEffect

useEffect(() => {
 if (!id) {
    navigate("/home");
  }
}, [id])

CodePudding user response:

import {Redirect} from "react-router-dom"

if(!id){
return <Redirect to="/" />
}

CodePudding user response:

I solved in in the router itself:

        <Route
          path={`${LocalRoutes.summary}/:id`}
          element={<Summary/>}
        />
        <Route path={LocalRoutes.summary} element={<Navigate to="/home" />} />
  • Related