React Modal with Bootstrap – Examples & Tutorial

To create a bootstrap modal in React, use the “reactstrap” libraryThe reactstrap library provides Button, Modal, ModalHeader, ModalBody, and ModalFooter components that we can use to create interactive bootstrap modals.

We will use the Laravel framework for the backend, and for a network request, we will use the Axios library to send an AJAX request to the Laravel API.

Here are the steps to create a React Modal with Bootstrap.

Step 1: Install React js Project

$ npx create-react-app reactjsbootstrapmodal

After creating a project, move to the project directory and type the following command to react server.

yarn start

Step 2: Install reactstrap and Bootstrap.

Change to your terminal and type the following command.

yarn add bootstrap@4.0.0

The above command adds Bootstrap 4 to our project.

yarn add reactstrap@next react react-dom

It will add reactstrap to our project.

Next, we will Import Bootstrap CSS in the src  >> index.js file.

import 'bootstrap/dist/css/bootstrap.css';

Step 3: Define a React Component to create a Modal

Go to the src  >> components folder and create a new file called ModalComponent.js. This file is generated for the Modal.

//ModalComponent.js
import React from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';

export default class ModalComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { modal: false,name: '',team :'' ,country: ''};

    this.toggle = this.toggle.bind(this);
    this.handleChangeName = this.handleChangeName.bind(this);
    this.handleChangeTeam = this.handleChangeTeam.bind(this);
    this.handleChangeCountry = this.handleChangeCountry.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  toggle() {
    this.setState({
      modal: !this.state.modal
    });
  }
  handleChangeName(event) {
    this.setState({name: event.target.value});
  }
  handleChangeTeam(event) {
    this.setState({team: event.target.value});
  }
  handleChangeCountry(event) {
    this.setState({country: event.target.value});
  }

  handleSubmit(event) {
    event.preventDefault();
     }


  render() {
    return (

        <div>
          <h1>React Bootstrap Modal Example</h1>
        <Button color="success" onClick={this.toggle}>React Modal</Button>
        <Modal isOpen={this.state.modal}>
        <form onSubmit={this.handleSubmit}>
          <ModalHeader>IPL 2018</ModalHeader>
          <ModalBody>
          <div className="row">
            <div className="form-group col-md-4">
            <label>Name:</label>
            <input type="text" value={this.state.name} onChange={this.handleChangeName} className="form-control" />
              </div>
              </div>
            <div className="row">
             <div className="form-group col-md-4">
            <label>Team:</label>
                <input type="text" value={this.state.team} onChange={this.handleChangeTeam} className="form-control" />
               </div>
              </div>
            <div className="row">
             <div className="form-group col-md-4">
              <label>Country:</label>
                <input type="text" value={this.country} onChange={this.handleChangeCountry} className="form-control" />
               </div>
              </div>
          </ModalBody>
          <ModalFooter>
            <input type="submit" value="Submit" color="primary" className="btn btn-primary" />
            <Button color="danger" onClick={this.toggle}>Cancel</Button>
          </ModalFooter>
          </form>
        </Modal>
        </div>
      
    );
  }
}

Next, we can add a component in the App.js file.

//App.js

import React, { Component } from 'react';
import './App.css';
import ModalComponent from './components/ModalComponent';

class App extends Component {
  render() {
    return (
      <div className="App">
          <ModalComponent/>        
      </div>
    );
  }
}

export default App;

Step 4: Install Laravel

Install Laravel by typing the following command.

composer create-project --prefer-dist laravel/laravel LaravelReactModal

Step 5: Configure the database.

Add database credentials in the .env file.

React Modal Tutorial

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravelreactmodal
DB_USERNAME=root
DB_PASSWORD=

Step 6: Create model and migration files

php artisan make:model FormModal -m

It will create a model and migration file.

Step 7: Establish the schema in the migration file

Go to the create_form_modals_table.php file and add the schema to it.

public function up()
    {
        Schema::create('form_modals', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('team');
            $table->string('country');
            $table->timestamps();
        });
    }

Step 8: Set the routes in the api.php file.

We can create a controller called FormModalController.php.

php artisan make:controller FormModalController --resource 

Add the following route in the api.php file.

Route::post('formmodal', 'FormModalController@store'); 

Code the store function inside that file.

public function store(Request $request)
    {
        $form = new FormModal();
        $form->name=$request->get('name');
        $form->team=$request->get('team');
        $form->country=$request->get('country');
        $form->save();
        return response()->json('Successfully added');

    }

Now, start the Laravel development server by typing the following command.

php artisan serve

Step 9: Add axios to a component file

You need axios. Move to your terminal and type the following command.

yarn add axios 

We can send a request using axios. But, first, we can import axios Package. Then, add the below code into a component file.

import axios from 'axios';
const form = {
      name: this.state.name,
      team: this.state.team,
      country: this.state.country
    }
    let uri = 'http://localhost:8000/api/formmodal';
    axios.post(uri, form).then((response) => {
     this.setState({
        modal: !this.state.modal
      });
    });

You can add the above code to a handleSubmit event.

The final code of the ModalComponent.js file looks like below.

//ModalComponent.js

import React from 'react';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import axios from 'axios';

export default class ModalComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { modal: false,name: '',team :'' ,country: ''};

    this.toggle = this.toggle.bind(this);
    this.handleChangeName = this.handleChangeName.bind(this);
    this.handleChangeTeam = this.handleChangeTeam.bind(this);
    this.handleChangeCountry = this.handleChangeCountry.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  toggle() {
    this.setState({
      modal: !this.state.modal
    });
  }
  handleChangeName(event) {
    this.setState({name: event.target.value});
  }
  handleChangeTeam(event) {
    this.setState({team: event.target.value});
  }
  handleChangeCountry(event) {
    this.setState({country: event.target.value});
  }

  handleSubmit(event) {
    event.preventDefault();
    const form = {
      name: this.state.name,
      team: this.state.team,
      country: this.state.country
    }
    let uri = 'http://localhost:8000/api/formmodal';
    axios.post(uri, form).then((response) => {
     this.setState({
        modal: !this.state.modal
      });
    });
  }


  render() {
    return (

        <div>
        <h1>React Bootstrap Modal Example</h1>
        <Button color="success" onClick={this.toggle}>Open Modal</Button>
        <Modal isOpen={this.state.modal}>
        <form onSubmit={this.handleSubmit}>
          <ModalHeader>IPL 2018</ModalHeader>
          <ModalBody>
          <div className="row">
            <div className="form-group col-md-4">
            <label>Name:</label>
            <input type="text" value={this.state.name} onChange={this.handleChangeName} className="form-control" />
              </div>
              </div>
            <div className="row">
             <div className="form-group col-md-4">
            <label>Team:</label>
                <input type="text" value={this.state.team} onChange={this.handleChangeTeam} className="form-control" />
               </div>
              </div>
            <div className="row">
             <div className="form-group col-md-4">
              <label>Country:</label>
                <input type="text" value={this.country} onChange={this.handleChangeCountry} className="form-control" />
               </div>
              </div>
          </ModalBody>
          <ModalFooter>
            <input type="submit" value="Submit" color="primary" className="btn btn-primary" />
            <Button color="danger" onClick={this.toggle}>Cancel</Button>
          </ModalFooter>
          </form>
        </Modal>
        </div>
      
    );
  }
}

You may meet the No ‘Access-Control-Allow-Origin’ header in the above tutorial on the requested resource. Origin ‘http://localhost:3000’ is therefore not allowed access. The response had an HTTP status code of 500. 

React Bootstrap Modal Laravel Tutorial

That’s it for this tutorial.

3 thoughts on “React Modal with Bootstrap – Examples & Tutorial”

  1. Hi, very good, but if I start the frontend I get a “TypeError: Cannot read property ‘apply’ of undefined” Stack enters with “const store createStore”. If need information about the circumstances we can talk you get my e-mail – Thank you. I work with Visual Studio Code and Chrome. Backend runs without a problem…

    I hope that is only an individual fault because of my configuration..
    Thank you – Greetings from Germany – J.Schatral

    Reply
  2. Hello,
    I tried this example but when I click on the React Modal button, the pop up shows up at the corner of the page. Any suggestions to make the popup overlay they at the center of the page the way a modal pop up should work?

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.