// MORE ON THE GITHUB REPO, LINK ATTACHED TO SOURCE // https://github.com/kouqhar/react-modal import { forwardRef, useImperativeHandle, useRef, useState } from "react"; import { createPortal } from "react-dom"; import styles from "./styles/styles.module.css" const Modal = forwardRef(function Modal({ text }, ref) { const [modalText, setModalText] = useState('') const dialog = useRef(); const ModalTextRef = useRef() function showModalText() { let inputValue = ModalTextRef.current.value // Validation and Sanitization if (typeof inputValue === "string") { setModalText(inputValue.toString()) ModalTextRef.current.value = "" } else return } // Exposing component APIs via the useImperativeHandle Hook // The method open is bound to the native showModal() useImperativeHandle(ref, () => { return { open() { dialog.current.showModal() } } }) return createPortal( <dialog ref={dialog} className={styles.dialog_modal}> <p>Content for your modal goes in here.</p> <p>You can also recieve props <b>{text}</b></p> <div className={styles.display_text}> {text.trim().length > 1 && <p>{modalText}</p>} </div> <input ref={ModalTextRef} placeholder="Enter text you want to be show . . ." /> <div className={styles.action_btn}> <form method="dialog"> <button>Close</button> </form> <button onClick={showModalText}>Show Text</button> </div> </dialog>, document.getElementById("react-modal")) }) export default Modal // With love @kouqharimport React from 'react'; class Modal extends React.Component { render() { // Render nothing if the "show" prop is false if(!this.props.show) { return null; } // The gray background const backdropStyle = { position: 'fixed', top: 0, bottom: 0, left: 0, right: 0, backgroundColor: 'rgba(0,0,0,0.3)', padding: 50 }; // The modal "window" const modalStyle = { backgroundColor: '#fff', borderRadius: 5, maxWidth: 500, minHeight: 300, margin: '0 auto', padding: 30 }; return ( <div className="backdrop" style={backdropStyle}> <div className="modal" style={modalStyle}> {this.props.children} <div className="footer"> <button onClick={this.props.onClose}> Close </button> </div> </div> </div> ); } } Modal.propTypes = { onClose: React.PropTypes.func.isRequired, show: React.PropTypes.bool, children: React.PropTypes.node }; export default Modal;