Modals are a common UI element used to display additional content or capture user input without navigating away from the current page.
In this tutorial, we’ll walk through the process of creating a reusable modal component in React.js. This component can be easily integrated into any React application, promoting code reusability and maintainability.
Contents
Create the Modal Component
- Inside the
src
folder, create a new directory namedcomponents
. - Inside the
components
directory, create a file namedModal.js
.
// src/components/Modal.js import React from 'react'; import './Modal.css'; const Modal = ({ isOpen, onClose, children }) => { if (!isOpen) return null; return ( <div className="modal-overlay"> <div className="modal-content"> <button className="close-button" onClick={onClose}> × </button> {children} </div> </div> ); }; export default Modal;
Style the Modal
- Create a file named
Modal.css
inside thecomponents
directory. - Style the modal overlay and content as desired. For example:
/* src/components/Modal.css */ .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; } .modal-content { background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); width: 80%; max-width: 400px; } .close-button { position: absolute; top: 10px; right: 10px; background: none; border: none; font-size: 18px; cursor: pointer; }
Using the Reusable Modal Component
- Open the
src
folder and create a file namedApp.js
. - Use the
Modal
component withinApp.js
:
// src/App.js import React, { useState } from 'react'; import './App.css'; import Modal from './components/Modal'; function App() { const [isModalOpen, setIsModalOpen] = useState(false); const openModal = () => { setIsModalOpen(true); }; const closeModal = () => { setIsModalOpen(false); }; return ( <div className="App"> <button onClick={openModal}>Open Modal</button> <Modal isOpen={isModalOpen} onClose={closeModal}> <h2>Hello from Modal!</h2> <p>This is a reusable modal component in React.</p> </Modal> </div> ); } export default App;
Test the Reusable Modal Component
- Run the development server
- Open your browser and navigate to
http://localhost:3000
. - Click the “Open Modal” button to see the reusable modal component in action.
Conclusion:
Congratulations! You’ve successfully created a reusable modal component in React.js.
You can now integrate this component into any React application to display modals with ease.
This promotes code reusability and enhances the maintainability of your projects. Feel free to customize the styling and functionality of the modal component to suit your specific needs.
Happy coding!
0 Comments