Using Bootstrap in a React App

Introduction

In this chapter, we will explore how to integrate Bootstrap 5 into a React application. Bootstrap is a popular CSS framework that helps in designing responsive and modern web applications. We will create a new React project from scratch, install Bootstrap, and use it to style a simple form, table, and a Todo app.

Table of Contents

  1. Setting Up a New React Project
  2. Installing Bootstrap
  3. Basic Configuration
  4. Creating a Simple Form
  5. Creating a Table
  6. Creating a Todo App
    • Adding Todos
    • Listing Todos
    • Deleting Todos
  7. Conclusion

Setting Up a New React Project

First, let’s create a new React project using the create-react-app tool.

  1. Open your terminal and run the following command:
    npx create-react-app bootstrap-react-app
    
  2. Navigate to the project directory:
    cd bootstrap-react-app
    

Installing Bootstrap

Next, let’s install Bootstrap 5. Open your terminal and run the following command inside your project directory:

npm install bootstrap

Basic Configuration

  1. Import Bootstrap CSS: Open src/index.js and import the Bootstrap CSS file:
    // src/index.js
    import 'bootstrap/dist/css/bootstrap.min.css';
    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from './App';
    import reportWebVitals from './reportWebVitals';
    
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      document.getElementById('root')
    );
    
    reportWebVitals();
    

    Explanation:

    • The Bootstrap CSS file is imported at the top to apply Bootstrap styles throughout the application.
  2. Run the Application: Start your React application by running:
    npm start
    

Creating a Simple Form

  1. Create a Form Component: In the src directory, create a new file named FormComponent.js.
  2. Define the Form Component: Add the following code to FormComponent.js to create a simple form using Bootstrap classes:
    // src/FormComponent.js
    import React from 'react';
    
    function FormComponent() {
      return (
        <div className="container mt-5">
          <h2>Bootstrap Form</h2>
          <form>
            <div className="mb-3">
              <label htmlFor="exampleInputEmail1" className="form-label">Email address</label>
              <input type="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" />
              <div id="emailHelp" className="form-text">We'll never share your email with anyone else.</div>
            </div>
            <div className="mb-3">
              <label htmlFor="exampleInputPassword1" className="form-label">Password</label>
              <input type="password" className="form-control" id="exampleInputPassword1" />
            </div>
            <div className="mb-3 form-check">
              <input type="checkbox" className="form-check-input" id="exampleCheck1" />
              <label className="form-check-label" htmlFor="exampleCheck1">Check me out</label>
            </div>
            <button type="submit" className="btn btn-primary">Submit</button>
          </form>
        </div>
      );
    }
    
    export default FormComponent;
    

    Explanation:

    • The form is styled using Bootstrap classes like container, mb-3, form-label, form-control, and btn btn-primary.
    • The form includes an email input, a password input, a checkbox, and a submit button.
  3. Use the Form Component in App.js: Open src/App.js and import the FormComponent:
    // src/App.js
    import React from 'react';
    import FormComponent from './FormComponent';
    
    function App() {
      return (
        <div>
          <FormComponent />
        </div>
      );
    }
    
    export default App;
    
  4. Save and View Changes: Save the files and go to your browser. You should see a Bootstrap-styled form.

Creating a Table

  1. Create a Table Component: In the src directory, create a new file named TableComponent.js.
  2. Define the Table Component: Add the following code to TableComponent.js to create a table using Bootstrap classes:
    // src/TableComponent.js
    import React from 'react';
    
    function TableComponent() {
      return (
        <div className="container mt-5">
          <h2>Bootstrap Table</h2>
          <table className="table">
            <thead>
              <tr>
                <th scope="col">#</th>
                <th scope="col">First</th>
                <th scope="col">Last</th>
                <th scope="col">Handle</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <th scope="row">1</th>
                <td>Mark</td>
                <td>Otto</td>
                <td>@mdo</td>
              </tr>
              <tr>
                <th scope="row">2</th>
                <td>Jacob</td>
                <td>Thornton</td>
                <td>@fat</td>
              </tr>
              <tr>
                <th scope="row">3</th>
                <td>Larry</td>
                <td>the Bird</td>
                <td>@twitter</td>
              </tr>
            </tbody>
          </table>
        </div>
      );
    }
    
    export default TableComponent;
    

    Explanation:

    • The table is styled using Bootstrap classes like table, thead, th, and td.
    • The table includes a header row and three rows of data.
  3. Use the Table Component in App.js: Open src/App.js and import the TableComponent:
    // src/App.js
    import React from 'react';
    import FormComponent from './FormComponent';
    import TableComponent from './TableComponent';
    
    function App() {
      return (
        <div>
          <FormComponent />
          <TableComponent />
        </div>
      );
    }
    
    export default App;
    
  4. Save and View Changes: Save the files and go to your browser. You should see a Bootstrap-styled table below the form.

Creating a Todo App

  1. Create a Todo Component: In the src directory, create a new file named TodoComponent.js.
  2. Define the Todo Component: Add the following code to TodoComponent.js to create a simple Todo app:
    // src/TodoComponent.js
    import React, { useState } from 'react';
    
    function TodoComponent() {
      const [todos, setTodos] = useState([]);
      const [inputValue, setInputValue] = useState('');
    
      const handleAddTodo = (event) => {
        event.preventDefault();
        if (inputValue.trim()) {
          setTodos([...todos, inputValue.trim()]);
          setInputValue('');
        }
      };
    
      const handleDeleteTodo = (index) => {
        setTodos(todos.filter((_, i) => i !== index));
      };
    
      return (
        <div className="container mt-5">
          <h2>Todo App</h2>
          <form onSubmit={handleAddTodo}>
            <div className="mb-3">
              <input
                type="text"
                className="form-control"
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                placeholder="Add a new todo"
              />
            </div>
            <button type="submit" className="btn btn-primary">Add Todo</button>
          </form>
          <ul className="list-group mt-3">
            {todos.map((todo, index) => (
              <li key={index} className="list-group-item d-flex justify-content-between align-items-center">
                {todo}
                <button className="btn btn-danger btn-sm" onClick={() => handleDeleteTodo(index)}>Delete</button>
              </li>
            ))}
          </ul>
        </div>
      );
    }
    
    export default TodoComponent;
    

    Explanation:

    • The TodoComponent uses the useState hook to manage the list of todos and the input value.
    • handleAddTodo adds a new todo to the list if the input is not empty.
    • handleDeleteTodo removes a todo from the list.
    • The form, input, button, and list are styled using Bootstrap classes.
  3. Use the Todo Component in App.js: Open src/App.js and import the TodoComponent:
    // src/App.js
    import React from 'react';
    import FormComponent from './FormComponent';
    import TableComponent from './TableComponent';
    import TodoComponent from './TodoComponent';
    
    function App() {
      return (
        <div>
          <FormComponent />
          <TableComponent />
          <TodoComponent />
        </div>
      );
    }
    
    export default App;
    
  4. Save and View Changes: Save the files and go to your browser. You should see a Todo app where you can add and delete todos.

Conclusion

In this chapter, we integrated Bootstrap 5 into a React application and used it to style a simple form, table, and Todo app. We created components for each feature and demonstrated how to use Bootstrap classes to achieve a modern and responsive design. By combining React and Bootstrap, you can quickly build stylish and functional web applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top