If you want to create a separate, generic Dialog component where you can pass in the title and description as props, you can do so by defining a reusable Dialog component. You can even pass HTML content in the description of the Dialog component, you can do so by utilizing React’s dangerouslySetInnerHTML
attribute. Here’s how you can achieve this:
-
Create a Generic Dialog Component:
// Dialog.js import React from 'react'; import { Dialog } from '@headlessui/react'; function CustomDialog({ title, description, isOpen, onClose }) { return ( <Dialog open={isOpen} onClose={onClose}> <Dialog.Overlay className="fixed inset-0 bg-black opacity-30" /> <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-white p-4"> <Dialog.Title>{title}</Dialog.Title> <Dialog.Description> <div dangerouslySetInnerHTML= /> </Dialog.Description> <button onClick={onClose}>Close</button> </div> </Dialog> ); } export default CustomDialog;
-
Use the Generic Dialog Component:
// Example.js import React, { Fragment, useState } from 'react'; import CustomDialog from './Dialog'; function Example() { const [isOpen, setIsOpen] = useState(false); return ( <Fragment> <button onClick={() => setIsOpen(true)}>Open Dialog</button> <CustomDialog isOpen={isOpen} onClose={() => setIsOpen(false)} title="Dialog Title" description="<p>This is the <strong>content</strong> of the dialog.</p>" /> </Fragment> ); } export default Example;
Inside the CustomDialog
component, we use dangerouslySetInnerHTML
to render the HTML content safely. However, please be cautious when using dangerouslySetInnerHTML
as it can expose your application to cross-site scripting (XSS) attacks if not used carefully. Make sure that you trust the source of the HTML content or sanitize it properly before rendering.