Table of contents
Create the modal component in your src folder, you could name it modal.js Like this:
In your modal component, structure your modal content like so: (basically what you want to be displayed on your modal) *Ignore the onChange function… it has nothing to do with displaying the modal.
Go ahead and use this CSS to style the modal-container and modal
Now how to display the modal onClick of a button: I need to create a component that will act as a parent to the modal(basically hosting the modal) I could call it anything… Page.js or anything.....
Now we have to import the modal component we created earlier into this page
Next, import useState from react like so: useState will be used to hold and set the state of the modal.
Next, Just above the return statement of the component and below the component function, declare the state for the modal like this:
Note: the state is set to false because I do not want the modal to be visible on page load(componentDidMount) but onClick of the show Modal button (your button could be called anything… in this case my button is :)
Next, we need to set the function to toggle the state so the modal can be visible when the button is clicked….. So we say :
const toggle = () => {
setModal(!modal)}
Take note of the exclamation mark before modal, this (!) is called the logical NOT operator what it’s simply doing here is changing state to FALSE if the current state is TRUE…Can be reversed too. Read up on MDN In our case we’re saying: If modal is false, setModal to true. Now, this toggle function will be passed into an onClick function and be called at every click of the button. after which we pass in the Modal component below the button like this and pass in props open that’ll take in the state modal:
and set the props to open. This prop would be passed in the modal page like so:
And, used in the modal page to wrap the modal container like this
Take note of the open props used to wrap the component {open && (
And that’s it…. Click on the button and have your modal.
How do I close the modal when its open?
Go to where you have the Modal component like this <Modal />
in the parent component(page.js in this case) and pass in a prop you could call it close(it’ll be used as a prop in closing our modal in our modal page)
like this:
Now, go to the modal page and on the export function where you added the open props, pass in the close props too like this:
Next, go to where you have the close icon for the modal and declare an onClick function that’ll take the close props. Like this:
And that’s all 🎉 Onclick of the button on the page hosting your modal, which in my case is: Your modal should open like this:
And onClick of the close icon, the modal goes away.
I hope this was helpful, happy coding✌🏼