Making a Custom Reusable Bootstrap Modal Component For React
Let’s start with our goal — Making a dynamic reusable custom modal component which can be reused our entire project.
When it’s needed this Modal Component:
We’re building a simple CRUD and the form is in the modal. We can do that in that form and create a simple modal on that form and manage that. This is really very easy.
But, problem is below -
- This modal Code Can not be reusable and only inside the component itself
- If we want to change styles of all of the component, we can not do that easily, we have to manually do that.
- It’s annoying to write the dame modal code again and again.
So, solve the problem and give a solution.
Step 1: Create a Demo React Project:
Create a demo react project using create-react-app, called — modal-demo
npx create-react-app modal-demo
Go to Project and start
cd modal-demo
npm start
Step 2: Install Additional Packages
Install Bootstrap and React Bootstrap
npm i bootstrap react-bootstrap
Step 3: Setup inde.js
Add bootstrap css in index.js. index.js file is like this -
Step 4: Setup Components
Main Simple Modal Component
Details About this Simple Modal Component:
- Line 2 — Use Bootstrap Modal Class
- Line 5 — Mange Dynamic Props to show modal, handle events, modal size and title
- Line 7 — Add Modal configuration based on the props value
- Line 9 — Display Modal title passed via modalTitle props.
- Line 14 — Display the child elements of this modal passed from parent component.
Step 5: Use this SimpleModal Component
Demo of this result:
So, clear the concept of using this Reusable Modal component
- We have to create first controller of off and on of the modal, using — show and setShow() function of useState().
- Then Just call the modal with passing necessary props.
- Write content inside the modal.
That’s it boom.
Test for More and More
Now Create More Components and check if this works as expected or not.
Create Task1Form.jsx component. and use this -
Task1Form Component
Task2Form Component
And in App.js
Final View
Task 2 View
Code Sandbox Link
That’s it, now you’ve created a custom modal component for your needs.
Any Comment or Suggestion, Please let me know.
Learn more about React Components from here — https://devsenv.com/tutorials/category/react-js