Saturday, February 1, 2020

ReactJS Create React Modal Open Popup Using reactjs-popup Dependency

In this tutorial, we will use the react-popup package which is a simple and Powerful react component. It's simple just add dependency

import Popup from "reactjs-popup";

which you can add to your project by following command

npm add reactjs-popup --save

Because reactjs-popup provides a child as function pattern, you have full control on Popup state
Full code example given below:
import React, { Component } from "react";
import "./styles.css";
import Popup from "reactjs-popup";

class App extends Component {
  constructor() {
    super();
    this.state = {
      open: false
    };
    this.openModal = this.openModal.bind(this);
    this.closeModal = this.closeModal.bind(this);
    this.popupOnClose = this.popupOnClose.bind(this);
  }

  openModal() {
    this.setState({ open: true });
  }

  closeModal() {
    this.setState({ open: false });
  }

  popupOnClose() {}

  render() {
    return (
      <div>
        <span onClick={this.openModal}>Click here to open Popup</span>
        <Popup
          open={this.state.open}
          className="popup-modal-container-box"
          modal
          onOpen={e => this.popupOnClose(e)}
          onClose={this.popupOnClose}
          lockScroll={true}
          closeOnDocumentClick={false}
        >
          <h1>HELLO POPUP</h1>
          <span onClick={this.closeModal}>CLOSE</span>
        </Popup>
      </div>
    );
  }
}
export default App;
Full example is created on CodeSandbox.IO
https://codesandbox.io/s/reactjs-create-react-modal-open-popup-using-reactjs-popup-dependency-qthyq

No comments:

Post a Comment