Complete the code to import the Next.js router hook needed to handle route changes.
import { [1] } from 'next/router';
The useRouter hook is used to programmatically navigate and intercept routes in Next.js.
Complete the code to define a modal component that uses state to control its visibility.
import { useState } from 'react'; export default function Modal() { const [isOpen, [1]] = useState(false); return isOpen ? <div role="dialog">Modal Content</div> : null; }
The setter function for isOpen state is conventionally named setIsOpen.
Fix the error in the code to correctly intercept route changes and open the modal.
import { useRouter } from 'next/router'; import { useState, useEffect } from 'react'; export default function Page() { const router = useRouter(); const [modalOpen, setModalOpen] = useState(false); useEffect(() => { const handleRouteChange = (url) => { if (url.includes('modal')) { setModalOpen(true); } else { setModalOpen(false); } }; router.events.[1]('routeChangeStart', handleRouteChange); return () => { router.events.off('routeChangeStart', handleRouteChange); }; }, [router]); return modalOpen ? <div role="dialog">Modal Open</div> : <div>Main Page</div>; }
In Next.js Pages Router, the router's event emitter uses router.events.on to listen for routeChangeStart events.
Fill both blanks to create an intercepting route link that opens the modal without full page reload.
import Link from 'next/link'; export default function Home() { return ( <Link href="/modal" [1]=[2]> Open Modal </Link> ); }
The shallow prop with value true allows route changes without full reload, useful for modals.
Fill the blanks to correctly implement a modal that closes on backdrop click and updates the route.
import { useRouter } from 'next/router'; export default function Modal() { const router = useRouter(); function closeModal() { router.[1]('/'); } return ( <div role="dialog" onClick={closeModal} aria-modal="true"> <div onClick={e => e.[2]()}> Modal Content <button onClick={closeModal} aria-label="Close modal">Close</button> </div> </div> ); }
Use replace to update the route without adding history entry, stopPropagation to prevent closing modal when clicking inside. push and preventDefault are distractors here.