DEV Community

Building a modal in React.

Prince on September 16, 2018

In this tutorial, we are going to build a modal in React. Below is a demo of it. Prerequisites These are the prerequisites required t...
Collapse
 
bthntprlk profile image
batu

Hi, nice article.

We prefer to use Modal components wrapped in a component which use ReactDOM.portal (comes with 16v) for better UI mechanism. Modals and popups are looks familiar but functionality. For example; you have a form in popup, and you have to show a modal if it’s successfully posted or failed badly. Modals needs to be above popup. We’ve created 2 roots like app-root; popup-root and modal-root in a large-scaled application. By this way render methods stay clean and UI flows properly without trading CSS hacks, thanks to DOM order.

Thank you for this article (:

Collapse
 
achowba profile image
Prince

Thanks for the comment, this is the first time I am hearing about ReactDOM.portal, I will go and check it out πŸ™‚.

Collapse
 
bthntprlk profile image
batu

(Y) basically it allows you to use components outside of your app-root.

See you (:

Collapse
 
velocity profile image
Bart Pelle • Edited

Nice write-up! But perhaps not the best to put the children in a <p>? Good article. :)

Collapse
 
achowba profile image
Prince

Noted...thanks πŸ™‚

Collapse
 
ditoorkodashvili profile image
Dito

Hi,
why use two functions (openModalHandler and closeModalHandler) when you can simply have:

toggleModal = () => {
this.setState(prevState=> {
isShowing: !prevState.isShowing
})
}

and also in this kind of situations wouldn't it be more optimal to use functional component with react hooks instead of class?

Collapse
 
achowba profile image
Prince

Thanks for the suggestion on using the conditional operator. Also, at the time this post was published, React Hooks didn't exist.

Collapse
 
kazimagha profile image
KazimAgha

Hi, if i want to add Function on Continue button how can i do that?
basically i want to display a dropdown menu as i click continue button

Collapse
 
achowba profile image
Prince

Hello
Add this below the closeModalHandler

continueFunction = () => {
    // your function body goes here
}
Enter fullscreen mode Exit fullscreen mode

and then change the continue button to this

<button className="btn-continue" onClick={props.close}>CONTINUE</button>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ishukanavs profile image
ishukanavs

My Page is very big and there is various open modal button in the center ,bottom and top . but the modal is open in top only... i want it scrollable as per where my button is.... like if i scroll down then this modal also go with it,... how can i do it??? @Atauba Prince