This tutorial shows how to build a basic React CRUD application with the React Hook Form library that includes pages for listing, adding, editing and deleting records from a JSON API. The records in the example app are user records, but the same CRUD pattern and code structure could be used to manage any type of data e.g. products, services, articles etc.
The example app runs with a fake backend api by default to enable it to run completely in the browser without a real api (backend-less), the fake api contains routes for user CRUD operations (Create, Read, Update, Delete) and it uses browser local storage to save data. To disable the fake backend you just have to remove a couple of lines of code from the root index.jsx file, you can refer to the fake-backend to see what’s required to build a real api for the example.
React Hook Form is a relatively new library for working with forms in React using React Hooks, I just stumbled across it recently and will be using it for my React projects going forward, I think it’s easier to use than the other options available and requires less code. For more info see https://react-hook-form.com.
The example app includes a basic home page and users section with CRUD functionality, the default page in the users section displays a list of all users and includes buttons to add, edit and delete users. The add and edit buttons navigate to a page containing a React Hook Form for creating or updating a user record, and the delete button executes a function within the user list component to delete the user record. The add and edit forms are both implemented with the same add/edit component which behaves differently depending on which mode it is in (“add mode” vs “edit mode”).
The example project is available on GitHub at https://github.com/cornflourblue/react-hook-form-crud-example.
Here it is in action:
(See on StackBlitz at https://stackblitz.com/edit/react-hook-form-crud-example)
npm install
from the command line in the project root folder (where the package.json is located).npm start
from the command line in the project root folder, this will launch a browser displaying the application.For more info on setting up your local React dev environment see React - Setup Development Environment.
#react