Next.js Discord

Discord Forum

best way to reuse shadcn dialogs

Unanswered
Abyssinian posted this in #help-forum
Open in Discord
Original message was deleted.

18 Replies

American black bear
add asChild to dialog trigger
<DialogTrigger asChild>{children}</DialogTrigger>
without the errors we can't help you much, but usually I would render the modal somewhere up the tree and keep it's state in a context which I can use throughout the application if needed.

For example:

export function Component1() {
  const {toggleModal} = useModal()

  return <button onClick={toggleModal}>Open Modal</button>
}

export function Component2() {
  const {toggleModal} = useModal()

  return <button onClick={toggleModal}>Open Modal</button>
}
American black bear
create a state use it as open
in your case pass it as props for welcome modal and into shadcn modal component
you can ask chatgpt to show you
American black bear
just pass it as props, that is the code
create state for it and pass it as props
ask chatgpt what props are or read docs
American black bear
here is the code chatgpt generated:

import React, { createContext, useContext, useState, ReactNode } from "react";
import { Dialog, DialogContent } from "@/components/ui/dialog"; // Using shadcn/ui for styling

// Create Context
const ModalContext = createContext<{ openModal: (content: ReactNode) => void; closeModal: () => void } | null>(null);

// Modal Provider
export function ModalProvider({ children }: { children: ReactNode }) {
  const [isOpen, setIsOpen] = useState(false);
  const [modalContent, setModalContent] = useState<ReactNode>(null);

  const openModal = (content: ReactNode) => {
    setModalContent(content);
    setIsOpen(true);
  };

  const closeModal = () => {
    setIsOpen(false);
    setModalContent(null);
  };

  return (
    <ModalContext.Provider value={{ openModal, closeModal }}>
      {children}
      <Dialog open={isOpen} onOpenChange={setIsOpen}>
        <DialogContent>{modalContent}</DialogContent>
      </Dialog>
    </ModalContext.Provider>
  );
};

// Hook to use modal
export function useModal() {
  const context = useContext(ModalContext);
  if (!context) throw new Error("useModal must be used within a ModalProvider");
  return context;
};
and if you keep planning on creating web applications read react docs or watch some guide. You cannot be creating stuff without knowing what context, props and state are.
by clicking a button
@American black bear https://react.dev/learn
American black bear
this is everything you need
you need to learn the basics if you plan to seriously build something
Original message was deleted
American black bear
.
no I wasen't and if you read what I said above you should've been able to come to a conclusion
you don't know react if you don't know what props are