Sunday, January 13, 2019

Create Simple Popup Example In React Application

In this tutorial we will see how to create simple popup in react application. Here we will provide you very simple and very easy example, that helps you to understand creation process of simple popup in react JS. We can use this kind of popup message to display email subscription notifications, display advertisements, confirmation message like YES/NO to user etc.
So in this example we have created component named as "Popup" and that helps to display the popup message, whenever user clicks on "Click To Launch Popup" button.

Simple Popup Example In React :

Lets see the project structure :
Create Simple Popup Example In React Application

Popup.js
This is a popup component that helps to display popup message to user.
import React from 'react';
import './style.css';

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 me</button>
        </div>
      </div>
    );
  }
}

export default Popup;

style.css 
This a style-sheet design for popup message.
.popup {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  background-color: rgba(0,0,0, 0.5);
}
.popup_inner {
  position: absolute;
  left: 25%;
  right: 25%;
  top: 25%;
  bottom: 25%;
  margin: auto;
  border-radius: 20px;
  background: white;
}

App.js 
This is a main component, where we have mentioned all event handler and states.
import React, { Component } from 'react';
import Popup from './components/Popup';


class App extends Component {

  constructor(props){
  super(props);
  this.state = { showPopup: false };
  }

  togglePopup() {
   this.setState({
     showPopup: !this.state.showPopup
   });
 }

  render() {
    return (
      <div>
       <h1> Simple Popup Example In React Application </h1>
       <button onClick={this.togglePopup.bind(this)}> Click To Launch Popup</button>

       {this.state.showPopup ?
         <Popup
          text='Click "Close Button" to hide popup'
          closePopup={this.togglePopup.bind(this)}
         />
         : null
       }
      </div>

    );
  }
}

export default App;

Output :
----------------------------
Create Simple Popup Example In React Application

Download Link :
https://github.com/skptricks/react/tree/master/Create%20Simple%20Popup%20Example%20In%20React%20Application

Demo Link :
https://skptricks.github.io/React-Popup/


This is all about Simple Popup Example In React Application. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment