cod;nncode. learn. thrive.

CRUD operation in React Js using Hooks, JSON file without APIs

Posted Mar 12, 2023

crud operation in react js using hooks

Are you looking to learn how to build a simple CRUD (Create, Read, Update, Delete) application in ReactJS using hooks and JSON file? Look no further!

In this tutorial, we will walk you through the process of building a simple Football Player Management System, where you can add, edit, and delete football players using ReactJS and a JSON file.

Key Takeaways

  • React Hooks provide a simple way to manage state and side effects in functional components.

  • Using a JSON file as a data source is a convenient way to store and retrieve data in a ReactJS application.

  • You can perform CRUD operations on JSON data by using the appropriate methods to add, read, update, and delete data.

  • Building a simple CRUD application in ReactJS involves creating components for adding, editing, and deleting data, as well as displaying data in a list or details view.

  • You can use conditional rendering to display different components based on the current state of the application.

  • By following this tutorial, you should have gained a solid foundation for building more complex ReactJS applications that involve CRUD operations and data management.

  • You can find the complete source code for this CRUD application on this GitHub .

CRUD Operation in React Js using Functional Component and Hooks

Before we get started, make sure you have the following installed:

  • Node.js and npm
  • A code editor (we recommend Visual Studio Code)

Let's get started!

Setting up the Project

First, create a new React project using the create-react-app command in your terminal:

npx create-react-app football-app

React js CRUD example with JSON file

Create a new file called 'players.json' in 'src/data' of your React project. This file will store all of our football player data.

{
  "players": [
    {
      "id": 1,
      "name": "Lionel Messi",
      "age": 34,
      "position": "Forward"
    },
    {
      "id": 2,
      "name": "Cristiano Ronaldo",
      "age": 36,
      "position": "Forward"
    },
    {
      "id": 3,
      "name": "Neymar Jr.",
      "age": 29,
      "position": "Forward"
    }
  ]
}

For the sake of simplicity, we have included only three football players in our JSON file.

Creating the "Read" i.e. Player List Component

Create a new file called PlayerList.js in the src folder of your React project.

This component will represent the list of football players in our player management system.

import React from "react";

const PlayerList = ({ players, onDelete, onEdit }) => {
  return (
    <div>
      <h2>Player List</h2>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
            <th>Position</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {players.map((player) => (
            <tr key={player.id}>
              <td>{player.id}</td>
              <td>{player.name}</td>
              <td>{player.age}</td>
              <td>{player.position}</td>
              <td>
                <button onClick={() => onEdit(player.id)}>Edit</button>
                <button onClick={() => onDelete(player.id)}>Delete</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <button onClick={onAdd}>Add New Player</button>
    </div>
  );
};

export default PlayerList;
  1. The PlayerList component is a functional component that takes three props as arguments: players, onDelete, and onEdit.

  2. The players prop is an array of objects containing information about each player. The onDelete prop is a function that is called when a player is to be deleted, and the onEdit prop is a function that is called when a player is to be edited.

  3. The component renders a heading "Player List" and a table that displays the details of each player in the players array. The table has five columns: ID, Name, Age, Position, and Actions.

  4. For each player in the players array, a table row is rendered with the player's details in each column. The ID, Name, Age, and Position are displayed in the first four columns. The Actions column contains two buttons: Edit and Delete.

  5. When the Edit button is clicked for a player, the onEdit function is called with the player's ID as an argument. Similar for the Delete button.

  6. When the 'Add New Player' button is clicked for a player, the onAdd function is called.

Overall, the PlayerList component is responsible for rendering the list of players and handling the user interactions for editing and deleting players.

Creating the "Create" Functionality

import { useState } from "react";

function AddPlayer({ addPlayer, onCancel }) {
  const [name, setName] = useState("");
  const [position, setPosition] = useState("");
  const [nationality, setNationality] = useState("");
  const [age, setAge] = useState("");

  function handleNameChange(e) {
    setName(e.target.value);
  }

  function handlePositionChange(e) {
    setPosition(e.target.value);
  }

  function handleNationalityChange(e) {
    setNationality(e.target.value);
  }

  function handleAgeChange(e) {
    setAge(e.target.value);
  }

  function handleSubmit(e) {
    e.preventDefault();
    addPlayer({
      name,
      position,
      nationality,
      age: Number(age),
    });
    setName("");
    setPosition("");
    setNationality("");
    setAge("");
  }

  return (
    <div>
      <h2>Add Player</h2>
      <form onSubmit={handleSubmit}>
        <div>
          <label>Name:</label>
          <input type="text" value={name} onChange={handleNameChange} />
        </div>
        <div>
          <label>Position:</label>
          <input type="text" value={position} onChange={handlePositionChange} />
        </div>
        <div>
          <label>Nationality:</label>
          <input
            type="text"
            value={nationality}
            onChange={handleNationalityChange}
          />
        </div>
        <div>
          <label>Age:</label>
          <input type="number" value={age} onChange={handleAgeChange} />
        </div>
        <button type="submit">Add</button>
        <button type="button" onClick={onCancel}>
          Cancel
        </button>
      </form>
    </div>
  );
}

export default AddPlayer;
  1. This component is called AddPlayer and it allows the user to add a new player to a list of players. The component receives two props: addPlayer and onCancel.

  2. The component uses the useState hook to define state variables for the name, position, nationality, and age of the new player. It also defines four functions to handle changes to each of these variables: handleNameChange, handlePositionChange, handleNationalityChange, and handleAgeChange.

  3. When the user submits the form by clicking the "Add" button, the handleSubmit function is called. This function prevents the default form submission behavior, calls the addPlayer function with the values of the input fields, and resets the input fields to their initial values.

The AddPlayer component returns a form with input fields for each of the player's attributes and two buttons: "Add" and "Cancel". When the "Add" button is clicked, the handleSubmit function is called. When the "Cancel" button is clicked, the onCancel function is called.

Creating the "Update" Functionality

  1. Create the EditPlayer component file In your React project, create a new file called EditPlayer.js in the src directory. This is where we'll define our component.

  2. Import the necessary modules At the top of your EditPlayer.js file, import React and useState. You can do this with the following code:

import React, { useState } from "react";
  1. Define the EditPlayer component Define a function called EditPlayer that takes three props: player, editPlayer, and onCancel. These props will be used to populate the form fields, update the player information, and cancel the editing process, respectively.

Inside the component function, create state variables for name, position, and age using the useState hook. You can initialize these state variables with the player prop that was passed in.

const EditPlayer = ({ player, editPlayer, onCancel }) => {
  const [name, setName] = useState(player.name);
  const [position, setPosition] = useState(player.position);
  const [age, setAge] = useState(player.age);

  // Rest of the component code goes here
};
  1. Create event handlers Next, create event handler functions for when the user changes the input fields. For example, you can create a function called handleNameChange that updates the name state variable whenever the user types in the Name input field.
const handleNameChange = (e) => setName(e.target.value);

Repeat this process for the Position and Age input fields.

  1. Create a submit handler Create a function called handleSubmit that is called when the user clicks the Save button. This function should prevent the default form submission behavior, create an updated player object using the state variables, and call the editPlayer prop function with the updated player object as an argument.
const handleSubmit = (e) => {
  e.preventDefault();
  const updatedPlayer = {
    id: player.id,
    name,
    position,
    age,
  };
  editPlayer(updatedPlayer);
};
  1. Render the form Finally, render the form with the input fields and buttons. Use the value prop to set the input field values to the corresponding state variables, and use the onChange prop to call the appropriate event handler function.
return (
  <div>
    <h2>Edit Player</h2>
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="name">Name:</label>
        <input type="text" id="name" value={name} onChange={handleNameChange} />
      </div>
      <div>
        <label htmlFor="position">Position:</label>
        <input
          type="text"
          id="position"
          value={position}
          onChange={handlePositionChange}
        />
      </div>
      <div>
        <label htmlFor="age">Age:</label>
        <input type="number" id="age" value={age} onChange={handleAgeChange} />
      </div>
      <div>
        <button type="submit">Save</button>
        <button type="button" onClick={onCancel}>
          Cancel
        </button>
      </div>
    </form>
  </div>
);
  1. Export the EditPlayer component.

Final EditPlayer Component -

import React, { useState } from "react";

const EditPlayer = ({ player, editPlayer, onCancel }) => {
  const [name, setName] = useState(player.name);
  const [position, setPosition] = useState(player.position);
  const [age, setAge] = useState(player.age);

  const handleNameChange = (e) => setName(e.target.value);
  const handlePositionChange = (e) => setPosition(e.target.value);
  const handleAgeChange = (e) => setAge(e.target.value);

  const handleSubmit = (e) => {
    e.preventDefault();
    const updatedPlayer = {
      id: player.id,
      name,
      position,
      age,
    };
    editPlayer(updatedPlayer);
  };

  return (
    <div>
      <h2>Edit Player</h2>
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="name">Name:</label>
          <input
            type="text"
            id="name"
            value={name}
            onChange={handleNameChange}
          />
        </div>
        <div>
          <label htmlFor="position">Position:</label>
          <input
            type="text"
            id="position"
            value={position}
            onChange={handlePositionChange}
          />
        </div>
        <div>
          <label htmlFor="age">Age:</label>
          <input
            type="number"
            id="age"
            value={age}
            onChange={handleAgeChange}
          />
        </div>
        <div>
          <button type="submit">Save</button>
          <button type="button" onClick={onCancel}>
            Cancel
          </button>
        </div>
      </form>
    </div>
  );
};

export default EditPlayer;

Creating the Delete Player Component

  1. Create a new file named "DeletePlayer.js".

  2. Import React by adding at the top of the file.

import React from "react";
  1. Define a functional component named "DeletePlayer" with the props "player", "deletePlayer", and "onCancel".
const DeletePlayer = ({ player, deletePlayer, onCancel }) => {
  1. Create a function named "handleDelete" that calls the "deletePlayer" function with the "player.id" as its argument when the "Delete" button is clicked.
const handleDelete = () => {
  deletePlayer(player.id);
};
  1. Add JSX

Inside the component's return statement, render a div that contains a heading with the text "Delete Player".

Add a paragraph that displays a confirmation message to the user with the name of the player to be deleted by using the "player.name" prop.

Add a button with the text "Delete" and attach the "handleDelete" function to its "onClick" event.

Add another button with the text "Cancel" and attach the "onCancel" function to its "onClick" event.

Export the "DeletePlayer" component by adding export default DeletePlayer; at the end of the file.

  return (
    <div>
      <h2>Delete Player</h2>
      <p>Are you sure you want to delete {player.name}?</p>
      <button onClick={handleDelete}>Delete</button>
      <button onClick={onCancel}>Cancel</button>
    </div>
  );
};

export default DeletePlayer;

Final DeletePlayer Component -

import React from "react";

const DeletePlayer = ({ player, deletePlayer, onCancel }) => {
  const handleDelete = () => {
    deletePlayer(player.id);
  };

  return (
    <div>
      <h2>Delete Player</h2>
      <p>Are you sure you want to delete {player.name}?</p>
      <button onClick={handleDelete}>Delete</button>
      <button onClick={onCancel}>Cancel</button>
    </div>
  );
};

export default DeletePlayer;

Connecting each component via App.js

  1. Inside App.js, import the necessary components using the following code:
import React, { useState, useEffect } from "react";
import PlayerList from "./components/PlayerList";
import EditPlayer from "./components/EditPlayer";
import AddPlayer from "./components/AddPlayer";
import DeletePlayer from "./components/DeletePlayer";
import data from "./data/players.json";
  1. Define the App function component using the useState hook to set the initial state of your component:
function App() {
  const [players, setPlayers] = useState(data.players);
  const [currentPlayer, setCurrentPlayer] = useState(null);
  const [showEditPlayer, setShowEditPlayer] = useState(false);
  const [showAddPlayer, setShowAddPlayer] = useState(false);
  const [showDeletePlayer, setShowDeletePlayer] = useState(false);
  const [playerToDelete, setPlayerToDelete] = useState(null);
  ...
}
  1. Create the following functions to handle different events:

handleDelete(id): Sets the playerToDelete state to id and the showDeletePlayer state to true.

const handleDelete = (id) => {
  setPlayerToDelete(id);
  setShowDeletePlayer(true);
};

deletePlayer(id): Removes the player with the specified id from the players state and sets the showDeletePlayer state to false.

const deletePlayer = (id) => {
  const updatedPlayers = players.filter((player) => player.id !== id);
  setPlayers(updatedPlayers);
  setShowDeletePlayer(false);
};

handleCancelDelete(): Sets the showDeletePlayer state to false.

const handleCancelDelete = () => {
  setShowDeletePlayer(false);
};

handleEdit(id): Sets the currentPlayer state to the player with the specified id and the showEditPlayer state to true.

const handleEdit = (id) => {
  const player = players.find((player) => player.id === id);
  setCurrentPlayer(player);
  setShowEditPlayer(true);
};

editPlayer(id, updatedPlayer): Updates the player with the specified id in the players state with updatedPlayer and sets the currentPlayer state to null and the showEditPlayer state to false.

const editPlayer = (updatedPlayer) => {
  const updatedPlayers = players.map((player) =>
    player.id === updatedPlayer.id ? updatedPlayer : player
  );
  setPlayers(updatedPlayers);
  setCurrentPlayer(null);
  setShowEditPlayer(false);
};

handleCancelEdit(): Sets the currentPlayer state to null and the showEditPlayer state to false.

const handleCancelEdit = () => {
  setCurrentPlayer(null);
  setShowEditPlayer(false);
};

handleAddPlayer(): Sets the showAddPlayer state to true.

const handleAddPlayer = () => {
  setShowAddPlayer(true);
};

addPlayer(player): Adds a new player to the players state and sets the showAddPlayer state to false.

const addPlayer = (player) => {
  const newPlayer = {
    id: Math.floor(Math.random() * 1000),
    ...player,
  };
  const updatedPlayers = [...players, newPlayer];
  setPlayers(updatedPlayers);
  setShowAddPlayer(false);
};

handleCancelAdd(): Hides the AddPlayer component on cancel button.

const handleCancelAdd = () => {
  setShowAddPlayer(false);
};
  1. JSX with conditions to show components based on user's action.
return (
    <div className="App">
      <h1>Football Team</h1>
      {showDeletePlayer ? (
        <DeletePlayer
          player={players.find((player) => player.id === playerToDelete)}
          deletePlayer={deletePlayer}
          onCancel={handleCancelDelete}
        />
      ) : showEditPlayer ? (
        <EditPlayer
          player={currentPlayer}
          editPlayer={editPlayer}
          onCancel={handleCancelEdit}
        />
      ) : showAddPlayer ? (
        <AddPlayer addPlayer={addPlayer} onCancel={handleCancelAdd} />
      ) : (
        <PlayerList
          players={players}
          onDelete={handleDelete}
          onEdit={handleEdit}
          onAdd={handleAddPlayer}
        />
      )}
    </div>
  );
}

export default App;

Final App Component -

import React, { useState, useEffect } from "react";
import PlayerList from "./components/PlayerList";
import EditPlayer from "./components/EditPlayer";
import AddPlayer from "./components/AddPlayer";
import DeletePlayer from "./components/DeletePlayer";
import data from "./data/players.json";

function App() {
  const [players, setPlayers] = useState(data.players);
  const [currentPlayer, setCurrentPlayer] = useState(null);
  const [showEditPlayer, setShowEditPlayer] = useState(false);
  const [showAddPlayer, setShowAddPlayer] = useState(false);
  const [showDeletePlayer, setShowDeletePlayer] = useState(false);
  const [playerToDelete, setPlayerToDelete] = useState(null);

  const handleDelete = (id) => {
    setPlayerToDelete(id);
    setShowDeletePlayer(true);
  };

  const deletePlayer = (id) => {
    const updatedPlayers = players.filter((player) => player.id !== id);
    setPlayers(updatedPlayers);
    setShowDeletePlayer(false);
  };

  const handleCancelDelete = () => {
    setShowDeletePlayer(false);
  };

  const handleEdit = (id) => {
    const player = players.find((player) => player.id === id);
    setCurrentPlayer(player);
    setShowEditPlayer(true);
  };

  const editPlayer = (updatedPlayer) => {
    const updatedPlayers = players.map((player) =>
      player.id === updatedPlayer.id ? updatedPlayer : player
    );
    setPlayers(updatedPlayers);
    setCurrentPlayer(null);
    setShowEditPlayer(false);
  };

  const handleCancelEdit = () => {
    setCurrentPlayer(null);
    setShowEditPlayer(false);
  };

  const handleAddPlayer = () => {
    setShowAddPlayer(true);
  };

  const addPlayer = (player) => {
    const newPlayer = {
      id: Math.floor(Math.random() * 1000),
      ...player,
    };
    const updatedPlayers = [...players, newPlayer];
    setPlayers(updatedPlayers);
    setShowAddPlayer(false);
  };

  const handleCancelAdd = () => {
    setShowAddPlayer(false);
  };

  return (
    <div className="App">
      <h1>Football Team</h1>
      {showDeletePlayer ? (
        <DeletePlayer
          player={players.find((player) => player.id === playerToDelete)}
          deletePlayer={deletePlayer}
          onCancel={handleCancelDelete}
        />
      ) : showEditPlayer ? (
        <EditPlayer
          player={currentPlayer}
          editPlayer={editPlayer}
          onCancel={handleCancelEdit}
        />
      ) : showAddPlayer ? (
        <AddPlayer addPlayer={addPlayer} onCancel={handleCancelAdd} />
      ) : (
        <PlayerList
          players={players}
          onDelete={handleDelete}
          onEdit={handleEdit}
          onAdd={handleAddPlayer}
        />
      )}
    </div>
  );
}

export default App;

And that's it!

Find the complete source code for this CRUD application on this GitHub .

By following the steps outlined in this tutorial, you will have a good understanding of how to use React hooks and manage state in a functional component. This is just the beginning of what you can achieve with React, so keep practicing and building more projects to improve your skills!

Conclusion

In this tutorial, we learned how to create a simple CRUD app in React using functional components and hooks. We also learned how to use a JSON file as the data source and how to perform CRUD operations on it.

This app is just a starting point, and there are many ways to improve it. For example, we could add pagination, search, and filtering functionality, or we could use a more advanced state management library like Redux or MobX.

I hope you found this tutorial helpful and that it gave you a good understanding of how to create CRUD apps in React using hooks and JSON data. If you have any questions or feedback, please feel free to leave a comment below.

FAQ:

Q: How to use JSON file in ReactJS? A: You can import JSON data into your ReactJS application using the "import" statement, and then access it like any other JavaScript object.

Q: How do you perform CRUD operations on JSON data? A: You can perform CRUD operations on JSON data in ReactJS using various methods like useState and useEffect hooks, and manipulating the data using JavaScript array methods.

Q: How do you make CRUD in React JS? A: To make CRUD in ReactJS, you need to define functions to handle each operation (Create, Read, Update, and Delete), and then call those functions in your component based on user interaction.

Q: How do I query JSON data in React? A: You can query JSON data in ReactJS using various methods like filtering and sorting using JavaScript array methods, or by using third-party libraries like lodash.

Further Resources

React 19: New Features List [Interview Ready]

Get interview-ready with our comprehensive guide on React 19, covering its groundbreaking advancements, new features, improved performance, and backward compatibility.

Read Here

Git How to Stash

The `git stash` command is used to stash changes in the working directory. This command saves changes in the stash stack, which can later be applied or popped.

Read Here

CRUD Operations in ReactJS Without API: GitHub Code Step-by-Step Example 2024

This article dives into implementing CRUD operations specifically in ReactJS without relying on an external API, providing a comprehensive step-by-step guide and a GitHub code example.

Read Here

Table Pagination tutorial in Reactjs using Server Side API data with Paginate, CSS example

Master the art of React pagination! Learn React.js pageable and paginate, style it with CSS, fetch data from APIs, and even implement server-side pagination with Node.js. Explore practical examples and level up your web development skills today.

Read Here

JavaScript Object Creation: Mastering Classes and Prototypes for Efficiency

Explore different methods of creating objects in JavaScript, with a focus on the 'class' keyword. Learn when to use each approach and the benefits they offer.

Read Here
Your feedback is our favorite notification! Share your thoughts about this page and make us smile.