Dev. to/ Michaelburr… By Michael Burrows
In this tutorial, we will build a custom reactive mode component that can be used to display various network elements, including forms, alert messages, or images.
Let’s start by setting up our application using the Create React App:
npx create-react-app react-modal
Copy the code
Create a new file called usemodal.js in the/SRC folder that will contain useModal () custom hooks. Custom hooks should always start with use, so you can quickly see that it is a reusable hook:
import { useState } from 'react'; const useModal = () => { const [visible, setVisible] = useState(false); function toggle() { setVisible(! visible); } return {toggle, visible} }; export default useModal;Copy the code
Also create a new file named modal.js for the Modal component itself in the/SRC folder:
import React from "react";
import ReactDOM from "react-dom";
const Modal = ({ visible, toggle }) => visible ? ReactDOM.createPortal(
<div className="modal">
<div className="modal-pop" role="dialog" aria-modal="true">
<h3>Hello World</h3>
<p>Et sit saepe velit tenetur et consequatur in. Nihil doloribus nulla nulla rem. Soluta illo et asperiores numquam earum nesciunt. Vero odio voluptatem sunt sunt laboriosam.</p>
<button type="button" onClick={toggle}>Close</button>
</div>
<div className="modal-overlay"></div>
</div>, document.body
) : null;
export default Modal;
Copy the code
If visible, we use Portal to render the schema as a DOM node that exists outside the parent component’S DOM hierarchy, in this case. This is because the mode needs to be the last DOM element in the page to satisfy accessibility requirements.
We can now pull it together by modifying the app.js file as follows:
import Modal from './Modal';
import useModal from './useModal';
import './App.css';
const App = () => {
const {toggle, visible} = useModal();
return (
<div className="App">
<button onClick={toggle}>Show Modal</button>
<Modal visible={visible} toggle={toggle} />
</div>
);
}
export default App;
Copy the code
Finally add some basic CSS to app.css so we can test the functionality:
.modal-pop {
background: #fff;
border: 2px solid #aaa;
border-radius: 5px;
z-index: 999;
max-width: 420px;
margin: auto;
padding: 1em 2em 2em;
position: relative;
}
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 99;
background-color: #000;
opacity: 0.75;
}
Copy the code
You can now test this pattern by running the NPM start command.
While this example is simple, it demonstrates how to build a functional modal component that you can customize for use in future projects. Thanks for reading, and be sure to check out my other tutorials on building the React component.