Home > Software design >  Disable route unless (condition) - React, Routing
Disable route unless (condition) - React, Routing

Time:01-13

The Issue:

I am facing an issue routing to a nested route (ExamResult component), I'd like to disable any kind of navigation to this specific route unless I've submitted a form.

Demo video:

https://www.screencast.com/t/cayuOnsa8

Code:

App.js Routes :

<Routes>

    ...

    <Route path='exams/:id' element={<ExamPage />} >
        <Route path='result' element={<ExamResult />} />
    </Route>
    <Route path='exams/:id/add-question' element={<RequireAuth><AddQuestion /></RequireAuth>}/>

    {/* <Route path='exams/:id/result' element={<ExamResult />} /> */}

    ...

    <Route path='*' element={<NoMatch />} />
</Routes>

QuestionList.js Component - Navigation to result route after quiz submission:

navigate('result', { state });

Repo: quiz-react-storybook Github Open Issue: issue

Expectations:

Only after I'm submitting the quiz I would expect the navigation to work, otherwise navigating to exams/:id/result path won't work.

CodePudding user response:

The ExamPage component must render an Outlet component for the nested routes to rendered. You could conditionally render the Outlet based on whether or not the form has been submitted.

...

{formSubmitted && <Outlet />}

...

An alternative method might be to pass some route state along with the route transition to the "exams/:id/result" route and check in ExamResult whether or not the navigation was valid and issue a back navigation if it wasn't.

navigate(
  'result',
  {
    state: {
      ...state,
      formSubmitted: true,
    }
  }
);

ExamResult

const navigate = useNavigate();
const { state } = useLocation();

useEffect(() => {
  if (!state?.formSubmitted) {
    navigate(-1);
  }
}, []);

...

CodePudding user response:

manage global state(ex. - Submitted: false) in context or redux to check whether the form is submitted or not. set this state to true on submit.

in result component based on condition return result's JSX or navigate to home if Submitted = false.

  • Related