Learn react on railsSort Order
00:00
14:27

React: Modal Box From Scratch Part 1

Being able to create your own reusable components is essential to being able to build custom user experiences. Modal boxes are useful tools for any site and generally in the jQuery hay days we used to just import a library someone created and put it in our application and call it a day, however today since we're in the process of learning react, let's take things further. In this episode we start to build our own custom modal box from scratch.

Learning how to build your own modal box will also allow you to customize it to your liking. Let's begin by installing classnames with yarn install classnames package.

Now we can begin implementing our modal box component.

import React from 'react'import classNames from 'classnames'import { observable, action } from 'mobx'import { observer } from 'mobx-react'@observerclass Modal extends React.Component {  @observable isOpen = false    @action open = (e) => {    if (e) { e.preventDefault() }        this.isOpened = true  }    @action close = (e) => {    if (e) { e.preventDefault() }        this.isOpen = false  }    render() {    const overlayClasses = classNames({ open: this.isOpen })        return (      <div id='modal' className={overlayClasses}>            </div>    )  }}export default Modal

Now let's import this component in our Welcome component.

// ...import Modal from './Modal'// ...class Welcome extends React.PureComponent {  openModal = (e) => {    e.preventDefault()        this.modal.open()  }  render() {    return (      // ...            <Modal ref={(node) => { this.modal = node }} />    )  }}

We can now see if the modal is being rendered. We can even click the button to see if it toggled the class.