Creating a CRUD Application with React and Bootstrap
Tags: learning, react, frontend
Published: 2023-09-29 13:37:44

In this article, we will create a simple CRUD (Create, Read, Update, Delete) application using React.js and Bootstrap. This application allows users to add, edit, delete, and view items with a FirstName and LastName. We will break down the code step by step to understand the key concepts.

## Setting Up the Project

First, make sure you have Node.js installed. If not, you can download and install it from [nodejs.org](nodejs.org). Then, create a new React application using `create-react-app`:

```
npx create-react-app crud-app
cd crud-app
npm install react-bootstrap bootstrap
```


Here, we're using react-bootstrap to style our components.

## Understanding the Code

## State Management

We begin by setting up the necessary state variables using the useState hook. For each item, we store firstName, lastName, and an array inputValue to store all items. The editIndex state variable is used to keep track of the item being edited.


```
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [inputValue, setInputValue] = useState([]);
const [editIndex, setEditIndex] = useState(-1);
```

## Handling Input Changes


We have two functions, handleFirstNameChange and handleLastNameChange, to handle changes in the FirstName and LastName input fields, respectively. These functions update the corresponding state variables.

```
const handleFirstNameChange = (e) => {
  setFirstName(e.target.value);
};

const handleLastNameChange = (e) => {
  setLastName(e.target.value);
};
```

## Adding and Updating Items

The handleInputValue function checks whether the FirstName and LastName are provided. If so, it either adds a new item to the inputValue array or updates an existing item, depending on whether editIndex is -1 or not.


```
const handleInputValue = () => {
  if (!firstName || !lastName) {
    return;
  }
  if (editIndex === -1) {
    // Adding a new item
    setInputValue((prevVal) => [
      ...prevVal,
      {
        firstName: firstName,
        lastName: lastName,
      },
    ]);
  } else {
    // Updating an existing item
    const updatedItems = [...inputValue];
    updatedItems[editIndex] = {
      firstName: firstName,
      lastName: lastName,
    };
    setInputValue(updatedItems);
    setEditIndex(-1);
  }

  setFirstName("");
  setLastName("");
};
```

## Deleting Items

The DeleteItem function removes an item at the specified index from the inputValue array and resets the editIndex.


```
const DeleteItem = (index) => {
  const filteredItems = [...inputValue];
  filteredItems.splice(index, 1);
  setInputValue(filteredItems);
  setEditIndex(-1);
};
```

## Editing Items

The handleEdit function sets the editIndex state variable to the index of the item being edited and populates the input fields with the corresponding values.


```
const handleEdit = (index) => {
  setEditIndex(index);
  setFirstName(inputValue[index].firstName);
  setLastName(inputValue[index].lastName);
};

```

## Building the User Interface

In the JSX code, we use Bootstrap components to create a user-friendly interface. Input fields for FirstName and LastName are provided along with buttons for adding, updating, and deleting items. A table displays the items with options to edit and delete each entry.


```
<input
  type="text"
  placeholder="Enter FirstName"
  value={firstName}
  onChange={handleFirstNameChange}
  className="p-1"
/>
<input
  type="text"
  placeholder="Enter LastName"
  value={lastName}
  onChange={handleLastNameChange}
  className="p-1"
/>
<Button variant="primary" onClick={handleInputValue}>
  {editIndex === -1 ? "Add" : "Update"}
</Button>
<Button variant="danger" onClick={handleDeleteAll}>
  DeleteAll
</Button>

```


Certainly! Below is the complete code for the CRUD application developed using React.js and Bootstrap, as explained in the article.


```
import "./styles.css";
import React, { useState } from "react";
import Button from "react-bootstrap/Button";

export default function App() {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [inputValue, setInputValue] = useState([]);
  const [editIndex, setEditIndex] = useState(-1);

  const handleFirstNameChange = (e) => {
    setFirstName(e.target.value);
  };

  const handleLastNameChange = (e) => {
    setLastName(e.target.value);
  };

  const handleInputValue = () => {
    if (!firstName || !lastName) {
      return;
    }
    if (editIndex === -1) {
      // Adding a new item
      setInputValue((prevVal) => [
        ...prevVal,
        {
          firstName: firstName,
          lastName: lastName
        }
      ]);
    } else {
      // Updating an existing item
      const updatedItems = [...inputValue];
      updatedItems[editIndex] = {
        firstName: firstName,
        lastName: lastName
      };
      setInputValue(updatedItems);
      setEditIndex(-1);
    }

    setFirstName("");
    setLastName("");
  };

  const handleDeleteAll = () => {
    setInputValue([]);
    setEditIndex(-1);
  };

  const handleEdit = (index) => {
    setEditIndex(index);
    setFirstName(inputValue[index].firstName);
    setLastName(inputValue[index].lastName);
  };

  const DeleteItem = (index) => {
    const filteredItems = [...inputValue];
    filteredItems.splice(index, 1);
    setInputValue(filteredItems);
    setEditIndex(-1);
  };

  return (
    <div className="App">
      <h1>CRUD App</h1>
      {/* input field */}
      <input
        type="text"
        placeholder="Enter FirstName"
        value={firstName}
        onChange={handleFirstNameChange}
        className="p-1"
      />
      &nbsp;
      <input
        type="text"
        placeholder="Enter LastName"
        value={lastName}
        onChange={handleLastNameChange}
        className="p-1"
      />
      &nbsp;
      {!firstName || !lastName ? (
        <Button variant="primary" onClick={handleInputValue} disabled>
          {editIndex === -1 ? "Add" : "Update"}
        </Button>
      ) : (
        <Button variant="primary" onClick={handleInputValue}>
          {editIndex === -1 ? "Add" : "Update"}
        </Button>
      )}
      &nbsp;
      {inputValue.length === 0 ? (
        <Button variant="danger" onClick={handleDeleteAll} disabled>
          DeleteAll
        </Button>
      ) : (
        <Button variant="danger" onClick={handleDeleteAll}>
          DeleteAll
        </Button>
      )}
      {/* Display content */}
      <div className="mt-3">
        {inputValue.length === 0 ? (
          <div className="h3">Add some content</div>
        ) : (
          <div className="container">
            <div className="card-body">
              <table className="table table-bordered">
                <thead>
                  <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th width="240px">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {inputValue.map((item, index) => {
                    return (
                      <tr key={index} className="al">
                        <td>{item.firstName}</td>
                        <td>{item.lastName}</td>
                        <td>
                          {editIndex === index ? (
                            <Button
                              variant="outline-danger"
                              style={{
                                marginRight: "5px",
                                height: "2.2rem"
                              }}
                              onClick={() => DeleteItem(index)}
                            >
                              <span role="img" aria-label="delete">
                                ❌
                              </span>
                            </Button>
                          ) : (
                            <>
                              <Button
                                variant="outline-primary"
                                style={{
                                  marginRight: "5px",
                                  height: "2.2rem"
                                }}
                                onClick={() => handleEdit(index)}
                              >
                                <span role="img" aria-label="edit">
                                  🖊️
                                </span>
                              </Button>
                              <Button
                                variant="outline-danger"
                                style={{
                                  marginRight: "5px",
                                  height: "2.2rem"
                                }}
                                onClick={() => DeleteItem(index)}
                              >
                                <span role="img" aria-label="delete">
                                  ❌
                                </span>
                              </Button>
                            </>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

```


---

## Conclusion

In this article, we have built a basic CRUD application using React.js and Bootstrap. We have covered state management, handling input changes, adding, updating, and deleting items. By understanding these concepts, you can create more complex applications with React.js. Remember, this is a fundamental example; you can further enhance and customize it based on your specific requirements. Happy coding!

**Follow Me on Social Media!**

If you found this article helpful, feel free to connect with me on LinkedIn and Twitter for more programming tips and tutorials. Let's learn and grow together!

LinkedIn: [https://www.linkedin.com/in/kartikbudhraja/](https://www.linkedin.com/in/kartikbudhraja/)

Twitter: [https://twitter.com/K_a_r_t_i_k_08](https://twitter.com/K_a_r_t_i_k_08)