Simple Popup Example In React

Byron Skoutaris
Nov 3 · 2 min read

In this tutorial we will be building a simple popup window written in React. It can be used to display email subscription notifications , display advertisements, offers, confirmation messages to user etc.

Lets see the project structure :

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_open'>
<h1>{this.props.text}</h1>
<button onClick={this.props.closePopup}>X</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_open {
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 </h1>
<button onClick={this.togglePopup.bind(this)}> Click To Open</button>
{this.state.showPopup ?
<Popup
text='X'
closePopup={this.togglePopup.bind(this)}
/>
: null
}
</div>
);
}
}
export default App;

Final Result:

Thank you for reading this simple tutorial for a popup feature written in React!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade