Bird
Raised Fist0
NextJSframework~10 mins

Modal pattern with intercepting routes in NextJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Modal pattern with intercepting routes
User clicks link
↓
Intercept route change
↓
Show modal overlay
↓
Render modal content
↓
User closes modal
↓
Restore previous page route
When a user clicks a link, the app intercepts the route change to show a modal overlay instead of a full page. Closing the modal restores the previous route.
Execution Sample
NextJS
import { useRouter } from 'next/navigation';
import { useState } from 'react';

export default function Page() {
  const router = useRouter();
  const [modalOpen, setModalOpen] = useState(false);

  function openModal() {
    setModalOpen(true);
    router.push('/modal-route');
  }

  function closeModal() {
    setModalOpen(false);
    router.back();
  }

  return (
    <>
      <button onClick={openModal}>Open Modal</button>
      {modalOpen && (
        <div role="dialog" aria-modal="true">
          <p>Modal Content</p>
          <button onClick={closeModal}>Close</button>
        </div>
      )}
    </>
  );
}
This code shows a button that opens a modal by intercepting route change and renders modal content. Closing the modal goes back to the previous route.
Execution Table
StepUser ActionState modalOpenRouter ActionRendered Output
1Page loadsfalseCurrent route '/'Button 'Open Modal' visible
2User clicks 'Open Modal'truerouter.push('/modal-route')Modal overlay with content shown
3User clicks 'Close' in modalfalserouter.back() to '/'Modal closes, back to main page
4User tries to navigate normallyfalseNormal route changePage changes normally, no modal
💡 Modal closes and route returns to previous page, normal navigation resumes.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
modalOpenfalsetruefalsefalse
router route'/''/modal-route''/'depends on user navigation
Key Moments - 3 Insights
Why does the modalOpen state change before the router.push?
Because setting modalOpen to true triggers React to render the modal overlay immediately, then router.push updates the URL. See execution_table step 2.
What happens if the user closes the modal but router.back() fails?
The modalOpen state is set to false, so the modal closes visually, but the URL might not change. This can cause mismatch. Always ensure router.back() works or handle fallback.
Why do we intercept route changes instead of normal navigation?
Intercepting lets us show modal content on top without full page reload, improving user experience. See concept_flow for the logical steps.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of modalOpen after the user clicks 'Open Modal'?
Aundefined
Btrue
Cfalse
Dnull
💡 Hint
Check execution_table row 2 under 'State modalOpen'
At which step does the router navigate back to the previous page?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at execution_table row 3 under 'Router Action'
If modalOpen was never set to true, what would happen when clicking 'Open Modal'?
AModal would open but URL stays the same
BBoth modal and URL change correctly
CModal would not open but URL changes
DNothing happens
💡 Hint
Refer to variable_tracker for modalOpen state changes and router actions
Concept Snapshot
Modal pattern with intercepting routes in Next.js:
- Intercept route changes to show modal overlay
- Use state (e.g., modalOpen) to control modal visibility
- Push new route for modal content
- Close modal by setting state false and router.back()
- Improves UX by avoiding full page reloads
Full Transcript
This visual execution shows how the modal pattern with intercepting routes works in Next.js. When the user clicks the 'Open Modal' button, the app sets modalOpen state to true and pushes a new route to show modal content. The modal appears as an overlay with accessible dialog roles. Closing the modal sets modalOpen to false and navigates back to the previous route. The execution table tracks each step, showing state changes and router actions. Key moments clarify why state changes happen before routing and why intercepting routes improves user experience. The visual quiz tests understanding of modalOpen state and router navigation steps.

Practice

(1/5)
1. What is the main benefit of using the modal pattern with intercepting routes in Next.js?
easy
A. It automatically reloads the entire page when opening a modal.
B. It allows showing a popup without leaving the current page.
C. It disables keyboard navigation while the modal is open.
D. It prevents any URL changes when interacting with the modal.

Solution

  1. Step 1: Understand modal with intercepting routes

    This pattern lets you open a modal that overlays the current page content without navigating away.
  2. Step 2: Identify the benefit

    Because the modal is shown on top, the user stays on the same page, improving user experience.
  3. Final Answer:

    It allows showing a popup without leaving the current page. -> Option B
  4. Quick Check:

    Modal pattern = popup without page change [OK]
Hint: Modals with intercepting routes keep you on the same page [OK]
Common Mistakes:
  • Thinking the page reloads when modal opens
  • Assuming URL never changes
  • Believing keyboard navigation is disabled
2. Which Next.js feature is commonly used to control modal visibility with intercepting routes?
easy
A. Using URL query parameters to toggle modal state
B. Using React class components with state
C. Using server-side rendering to open modals
D. Using CSS hover effects to show modals

Solution

  1. Step 1: Identify modal control method

    Next.js modals with intercepting routes often use URL query parameters to track if modal is open or closed.
  2. Step 2: Eliminate incorrect options

    React class components are outdated; server-side rendering doesn't control modal visibility dynamically; CSS hover is unrelated to routing.
  3. Final Answer:

    Using URL query parameters to toggle modal state -> Option A
  4. Quick Check:

    Modal visibility = URL query param [OK]
Hint: Modal open state is often in URL query parameters [OK]
Common Mistakes:
  • Confusing client state with URL state
  • Using class components instead of hooks
  • Relying on CSS hover for modal control
3. Given this Next.js snippet controlling a modal with query param ?modal=open:
const router = useRouter();
const isModalOpen = router.query.modal === 'open';

return (
  <>
    {isModalOpen && <ModalComponent />}
    <MainPageContent />
  </>
);
What happens when the URL changes from /page to /page?modal=open?
medium
A. The page reloads and shows a blank screen.
B. The main page content is replaced by the modal component.
C. Nothing changes because query parameters don't affect rendering.
D. The modal component appears over the main page content.

Solution

  1. Step 1: Understand the code logic

    The code checks if the query parameter 'modal' equals 'open'. If yes, it renders the modal component alongside the main content.
  2. Step 2: Analyze URL change effect

    Changing URL to include '?modal=open' sets isModalOpen true, so modal appears over the main page without replacing it.
  3. Final Answer:

    The modal component appears over the main page content. -> Option D
  4. Quick Check:

    Query param 'modal=open' = modal visible [OK]
Hint: Query param 'modal=open' triggers modal display [OK]
Common Mistakes:
  • Thinking modal replaces main content
  • Ignoring query parameters in rendering
  • Assuming page reloads on query change
4. Consider this Next.js modal code snippet:
const router = useRouter();
const isModalOpen = router.query.modal === 'open';

function closeModal() {
  router.push('/page');
}

return (
  <>
    {isModalOpen && <Modal onClose={closeModal} />}
    <PageContent />
  </>
);
What is a likely bug in this code regarding accessibility?
medium
A. The URL does not update when the modal opens.
B. The modal never closes because router.push is incorrect.
C. Keyboard focus is not moved to the modal when it opens.
D. The modal content is rendered outside the React tree.

Solution

  1. Step 1: Review modal accessibility needs

    When a modal opens, keyboard focus should move inside it for screen reader and keyboard users.
  2. Step 2: Check code for focus management

    The code changes URL and renders modal but does not handle moving keyboard focus to modal.
  3. Final Answer:

    Keyboard focus is not moved to the modal when it opens. -> Option C
  4. Quick Check:

    Modal accessibility = move keyboard focus [OK]
Hint: Always move keyboard focus into modal on open [OK]
Common Mistakes:
  • Ignoring keyboard focus management
  • Assuming URL push closes modal automatically
  • Confusing rendering with accessibility
5. You want to implement a modal in Next.js that opens on /gallery?modal=photo123 and closes by removing the query param, without losing the gallery scroll position. Which approach best achieves this?
hard
A. Use router.push with shallow: true to update URL without full reload and keep scroll.
B. Use router.replace without shallow to reload page and reset scroll.
C. Use window.location.href to change URL and force reload.
D. Use CSS to hide modal and ignore URL changes.

Solution

  1. Step 1: Understand shallow routing in Next.js

    Shallow routing updates the URL without running data fetching methods or reloading the page, preserving scroll and state.
  2. Step 2: Apply shallow routing to modal open/close

    Using router.push with shallow: true changes query params to open/close modal without losing scroll position.
  3. Final Answer:

    Use router.push with shallow: true to update URL without full reload and keep scroll. -> Option A
  4. Quick Check:

    Shallow routing = URL change without reload [OK]
Hint: Use shallow routing to keep scroll when changing URL [OK]
Common Mistakes:
  • Using router.replace without shallow reloads page
  • Using window.location.href causes full reload
  • Ignoring URL for modal state control
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard