Next.js Discord

Discord Forum

Hydration error shadcn modal

Answered
Almond stone wasp posted this in #help-forum
Open in Discord
Almond stone waspOP
I am trying to add a shadcn modal, <Modal/> is in server component and in modal component i am getting params to get an id and the condition is based on id, like if id is there then only open the modal

Modal is triggering, but its not showing and when i refresh i am getting hydration error

// main page (server component)
export default async function Page() {
  return(
     // other components 
    <Modal/>
)
} 

// modal (client component)
"use client"
import { useSearchParams } from "next/navigation";

export default function Modal(){
  const searchParams = useSearchParams();
  const [open, setOpen] = useState(!!searchParams.get("id"));

  return(
    <Dialog open={open} onOpenChange={() => setOpen(false)}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>This is modal</DialogTitle>
          <DialogDescription>
            This is modal description
          </DialogDescription>
        </DialogHeader>
      </DialogContent>
    </Dialog>  
  )
}

// triggering modal via Link
"use client"
export default function (){
  return (
    // other components
    <Link href={`${pathname}?id=123`}>View Modal</Link>
)
}
Answered by joulev
Shadcn modal is based on radix dialog. Radix dialog currently has a bug that prevents it from being open during server rendering, hence you must initialise open to false and open the dialog manually on load using a useEffect
View full answer

8 Replies

Unsure on the modal, but by any chance do you have a password manager like lastpass installed. That causes like 99% of my hydration errors.
nope
@!=tgt nope
my reply was to the OP. I'm only suggesting it for his hydration issue because I just went through the exact same thing.
Answer
Almond stone waspOP
@joulev
thanks
it's working