Next.js Discord

Discord Forum

Closing modal (parallel route) when link navigation

Unanswered
Britannia Petite posted this in #help-forum
Open in Discord
Britannia PetiteOP
Hi, im suing next.js how to close a modal (using parrallel route @slot) when clicking on a link using this folder structure :

/app
layout.tsx
- /(main)
-- layout.tsx // check layout code below 
-- /(home)
--- page.tsx
-- /@modal
--- /(.)photo 
---- /[id]
----- page.tsx
-- /whatever



export default function Layout ({children, modal) {
  return (
    <div>
      {children}
       {modal}       
    <div>
  )

}


Right know if im on page.tsx in /(home) and im clicling on link
<Link href='/photo/123'>link</Link>
the modal is opening (normal behavior, OK).
If from this page with the opened modal im clicking on
<Link href='/whatever'>link</Link>
the modalis closing.
but If from /whatever I click back on home, the modal is still opened .. could help me with this ?

3 Replies

Britannia PetiteOP
OK! After few days I finally foudn a workaround ! follwing this video : https://www.youtube.com/watch?v=v02LJJMz_sc
the trick is to use <dialog> tag for your modal, and then listen for route change and close it with modalRef.current.close() when leaving the route where you modal is ! hope it helps someone
    useEffect(() => {
        console.log(`Route changed to: ${pathname}`);
        if (!pathname.includes('game')) {
            // router.back();
            console.log('route changed...');
            modalRef.current.close();
        } else {
            modalRef.current.show();
        }
    }, [pathname, router]);