DEV Community

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

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

8 3

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:)

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay