DEV Community

Cover image for Create Popup or Modal Component in React
Chetan Rohilla
Chetan Rohilla

Posted on • Updated on • Originally published at w3courses.org

Create Popup or Modal Component in React

Popup is a UI Component which displays as window in different sizes and screen positions on websites or apps. We can display different any components like forms, boxes, images, videos, tables etc. in Popup. Here we will create popup component in react.

class Popup extends React.Component {
  render() {
    return (
      <div className='popup'>
        <div className='popup_inner'>
          <h1>{this.props.text}</h1>
        <button onClick={this.props.closePopup}>Close</button>
        </div>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Now, we have <Popup /> Component and we can use this in our class or functional components. We can also add any elements or components in our Popup like offer details, images, videos, newsletter forms etc. For example here we are using <Popup /> react component in App Component.

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      showPopup: false
    };
  }
  togglePopup() {
    this.setState({
      showPopup: !this.state.showPopup
    });
  }
  render() {
    return (
      <div className='app'>
        <button onClick={this.togglePopup.bind(this)}>Show Popup</button>

        {this.state.showPopup ? 
          <Popup
            text='This is React Popup'
            closePopup={this.togglePopup.bind(this)}
          />
          : null
        }
      </div>
    );
  }
};
Enter fullscreen mode Exit fullscreen mode

React Popup Component CSS

.popup {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  padding: 1rem;
  background-color: rgba(0,0,0, 0.5);
}

.popup_inner {
  position: absolute;
  left: 25%;
  right: 25%;
  top: 25%;
  bottom: 25%;
  margin: auto;
  background: white;
  padding: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

Please like share subscribe and give positive feedback to motivate me to write more for you.

For more tutorials please visit my website.

Thanks:)
Happy Coding:)

Top comments (0)