All files / src/components/Dynamic DynamicPopup.js

0% Statements 0/10
0% Branches 0/4
0% Functions 0/5
0% Lines 0/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56                                                                                                               
import React, { useState, useImperativeHandle, forwardRef } from 'react'
import { CModal, CModalHeader, CModalBody } from '@coreui/react'
 
/**
 * A reusable modal (popup) component that can be programmatically opened and closed using `ref`.
 *
 * This component leverages `forwardRef` and `useImperativeHandle` to expose `open()` and `close()` methods
 * to parent components. The modal is only rendered when it is visible.
 *
 * @component
 * @example
 * const popupRef = useRef();
 *
 * <DynamicPopup ref={popupRef} title="My Popup">
 *   <p>Popup content goes here</p>
 * </DynamicPopup>
 *
 * // To open the modal from the parent:
 * popupRef.current.open();
 *
 * // To close the modal:
 * popupRef.current.close();
 *
 * @param {Object} props
 * @param {string} [props.title] - Title displayed in the modal header.
 * @param {'sm' | 'lg' | 'xl'} [props.size] - Optional size of the modal.
 * @param {React.ReactNode} props.children - The content to be rendered inside the modal body.
 *
 * @returns {JSX.Element|null} Returns the modal when visible, otherwise `null`.
 */
 
const DynamicPopup = forwardRef(({ title, size, children }, ref) => {
	const [show, setShow] = useState(false) // Internal visibility state
 
	// Expose `open` and `close` methods to parent via ref
	useImperativeHandle(ref, () => ({
		open: () => setShow(true),
		close: () => setShow(false),
	}))
 
	// If not visible, don't render the modal at all
	if (!show) return null
 
	return (
		<CModal visible={show} onClose={() => setShow(false)} backdrop="static" size={size}>
			{title && (
				<CModalHeader className="d-flex justify-content-between align-items-center">
					<strong>{title}</strong>
				</CModalHeader>
			)}
			<CModalBody>{children}</CModalBody>
		</CModal>
	)
})
 
export default DynamicPopup