Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to launch a demo modal when on click of a button in ReactJS

Understanding the Task

Let's get started on a fun and practical task: we want to launch a demo modal when a button is clicked in a ReactJS application. If you're unfamiliar with the term, a 'modal' is a fancy word for a pop-up window that's layered on top of the main content. It usually requires user interaction before they can return to using the main interface.

Setting up the React Component

The first thing we need is a React component. This component will contain our button and the modal we wish to display. Think of a component like a mini-program inside our larger program. It's a self-contained chunk of code that specifies how a certain part of our user interface should look and behave.

Let's create a simple App component.

import React from 'react';
import './App.css';

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <button>Open Modal</button>
      </div>
    );
  }
}

export default App;

Here, we have a basic React component with a single button. When we click this button, we want a modal to pop up. However, we haven't defined what should happen when the button is clicked yet.

React State and Handling Events

To handle a button click event in React, we need to understand two important concepts: state and event handlers.

State is like the memory of a component. It holds information that can change over time and affect what is rendered on the screen.

An event handler is like a helper who listens for certain events, like clicks, and performs actions when those events occur.

In our case, we'll use state to keep track of whether the modal is open or not, and an event handler to change that state when the button is clicked.

Let's implement this:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { isModalOpen: false };
    this.handleButtonClick = this.handleButtonClick.bind(this);
  }

  handleButtonClick() {
    this.setState({ isModalOpen: true });
  }

  render() {
    return (
      <div className="App">
        <button onClick={this.handleButtonClick}>Open Modal</button>
      </div>
    );
  }
}

In the constructor, we initialize our state with isModalOpen: false, meaning the modal is not open when the app starts.

We also bind this to our event handler handleButtonClick. Binding is necessary in JavaScript classes to make sure this inside the method points to the class instance.

Then, we attach handleButtonClick to the button's onClick prop. Now, whenever the button is clicked, handleButtonClick will be called, setting isModalOpen to true.

Creating Our Modal

All that's left is to create the modal itself. For simplicity, let's make our modal a simple div that covers the entire screen with a semi-transparent background. When isModalOpen is true, we'll show this div. Otherwise, we'll hide it.

class App extends React.Component {
  // ... same as before ...

  render() {
    return (
      <div className="App">
        <button onClick={this.handleButtonClick}>Open Modal</button>

        {this.state.isModalOpen && (
          <div className="modal">
            <p>This is a modal!</p>
          </div>
        )}
      </div>
    );
  }
}

Here, we're using JavaScript's && operator to conditionally render the modal div. If isModalOpen is true, the modal will be rendered. If it's false, the modal won't be rendered.

To make the modal look like a modal, let's add some styles to App.css:

.modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}

Wrapping It Up

That's it! Now you have a functional modal that opens when a button is clicked.

Remember, programming is like building with Lego blocks. Every new concept or feature you learn is another block in your toolkit. The more blocks you have, the more complex and interesting structures you can build. In this tutorial, you've added a very common and useful block to your toolkit: the modal. You've also learned about React state, event handling, and conditional rendering, which are important tools for building interactive user interfaces in React.

So, keep practicing, keep building, and most importantly, have fun! Your journey as a programmer is just beginning, and the possibilities are endless. Happy coding!