Use React to write a dialog box or modal box

Keywords: Javascript React

It's been a long time since I planned to use React to write dialog boxes. Now it's time to fulfill my promise. In fact, it's quite simple to write.

The core is to use the interface of React.createPortal(element, domContainer). This interface embeds the element rendered DOM node into the domcontainer (usually document.body) and ensures that it is embedded only once.

Welcome to subscribe My blog.

So, we can write a dialog box or a modal box like this:

function Dialog() {
    return React.createPortal( <div>Dialog contents</div>, document.body )
}

A new div will appear inside the body:

A complete DEMO:


Click to run DEMO


class Modal extends React.Component {
  render() {
    const {
      visible,
      onClose
    } = this.props
    return visible && ReactDOM.createPortal(<StyledModalRoot>
      <div className="box">
        Content
        <br/>
        <button onClick={onClose}>Close</button>
      </div>
    </StyledModalRoot>, document.body)
  }
}

class App extends React.Component {
  state = {
    visibleModal: false
  }
  showModal = () => this.setState( { visibleModal: true } )
  handleCloseModal = () => this.setState( { visibleModal: false } )
  render() {
    const { visibleModal } = this.state
    return <div style={{padding: '20px'}}>
    <button onClick={ this.showModal }>Show Modal</button>
    <Modal visible={visibleModal} onClose={ this.handleCloseModal } />
  </div>
  }
}

const StyledModalRoot = styled.div`
  position: fixed;
  z-index: 1001;
  left: 0;
  top: 0;
  display: grid;
  place-items: center;
  width: 100%;
  height: 100%;
  background: rgba( 0, 0, 0, 0.2 );

  >.box {
    position: relative;
    display: grid;
    place-items: center;
    width: 80%;
    height: 80%;
    background: white;
    border-radius: 10px;
    box-shadow: 0px 3px 5px -1px rgba(0,0,0,0.2), 0px 5px 8px 0px rgba(0,0,0,0.14), 0px 1px 14px 0px rgba(0,0,0,0.12);
  }
`

Thank you for taking the time to read this article. If you like this article, welcome to like, collect and share, let more people see this article, this is also my biggest encouragement and support!
Welcome to Star and subscription My original front end technology blog.

Posted by kh411dz on Sat, 23 Nov 2019 08:01:53 -0800