How to do crud operations in ReactJS ?
CRUD stands for Create, Read, Update, and Delete. In ReactJS everything is aligned in a form of a component and every component has its own way and feature to do so.
React js is one of the most used JavaScript libraries for frontend development. It’s very important to have the basic functionality of CRUD operations in with react-js. In this article, we don’t use any JSON-server or Axios for performing the CRUD operation. We will use a simple JavaScript object to do so.
For learning CRUD operation with ReactJS and NodeJS please refer to How to build a basic CRUD app with Node.js and ReactJS?
- Create: Creating a post or adding the table row, adding data into the webpage, or creating content.
- Read: Reading or retrieving data from web-page
- Update: Updating or editing existing content in the webpage
- Deleting: Deleting and removing the entry or content/post from the webpage
In this article, we will be learning to add the name and age of a user and perform CRUD operations into it.
Step 1: Setting up a project
Make sure you have node-js installed on your computer in order to create react app. Enter these commands for creating react app
npx create-react-app crud_app or yarn create react-app crud_app
After important installations, enter these commands on terminal/cmd
cd crud_app npm start or yarn start
This will start the application
Step 2: Project structure
You may get rid of other files like the logo, and other test files and delete them. Here are 4 files in components that are a core of this application in the source folder.
- array.js – This file is not a react file but a simple JavaScript object file (Our temporary data source). This object has 3 key-values id, name, and age.
- Create.js – This file consist logic for creating the post or adding a table row in out app.
- Edit.js – This file is responsible for editing the existing entry.
- Home.js – This file is a reading file and responsible for showing an information/data.
Step 3: Installing dependency
First of all download this dependency-
Dependency | Installation command | Using purpose |
---|---|---|
React-Bootstrap | npm install react-bootstrap bootstrap@5.1.3 or yarn add react-bootstrap bootstrap@5.1.3 | Bootstrap is a CSS framework that react-router will help us for focusing on functionality rather than on CSS. |
React Router Dom | npm install react-router-dom or yarn add react-router-dom | We use react router dom for various packages and modules like routers for routing, useNavigations and etc. |
Now, after installations, please create make a folder inside an src folder naming components. Then make 4 js files
Create.js Edit.js Home.js array.js
Step 4: Component files – creating files
array.js
// Javascript object named array with 3 key-values const array = [ { id: '1' , Name: 'Shivansh' , Age: '23' }, { id: '2' , Name: 'Simran' , Age: '22' }, { id: '3' , Name: 'Aakash' , Age: '23' } ] export default array |
app.js:This file is used to manage all other component files and provide routing to all other components.
app.js
// important imports import React from 'react' import { BrowserRouter as Router,Route, Routes } from 'react-router-dom' ; import './App.css' ; import Create from './components/Create' ; import Edit from './components/Edit' ; import Home from './components/Home' ; function App() { return ( <div className= 'App' > <Router> <Routes> <Route path= '/' element={<Home/>}/> <Route path= '/create' element={<Create/>}/> <Route path= '/edit' element={<Edit/>}/> </Routes> </Router> </div> ); } export default App; |
Step 5: Create component
Create.js
import React, { useState } from 'react' import { Button, Form } from 'react-bootstrap' import 'bootstrap/dist/css/bootstrap.min.css' ; import array from './array' ; import { v4 as uuid } from 'uuid' ; import { Link, useNavigate } from 'react-router-dom' ; function Create() { // Making usestate for setting and // fetching a value in jsx const [name, setname] = useState( '' ); const [age, setage] = useState( '' ); // Using useNavigation for redirecting to pages let history = useNavigate(); // Function for creating a post/entry const handelSubmit = (e) =>{ e.preventDefault(); // Prevent reload const ids = uuid() // Creating unique id let uni = ids.slice(0,8) // Slicing unique id // Fetching a value from usestate and // pushing to javascript object let a = name, b=age array.push({id:uni,Name:a,Age:b}) // Redirecting to home page after creation done history( '/' ) } return ( <div > <Form className= "d-grid gap-2" style={{margin: '15rem' }}> { /* Fetching a value from input textfirld in a setname using usestate*/ } <Form.Group className= "mb-3" controlId= "formBasicName" > <Form.Control onChange={e => setname(e.target.value)} type= "text" placeholder= "Enter Name" required/> </Form.Group> { /* Fetching a value from input textfirld in a setage using usestate*/ } <Form.Group className= "mb-3" controlId= "formBasicAge" > <Form.Control onChange={e => setage(e.target.value)} type= "text" placeholder= "Age" required/> </Form.Group> { /* handing a onclick event in button for firing a function */ } <Button onClick={e => handelSubmit(e)} variant= "primary" type= "submit" > Submit </Button> { /* Redirecting back to home page */ } <Link className= "d-grid gap-2" to= '/' > <Button variant= "info" size= "lg" > Home </Button> </Link> </Form> </div> ) } export default Create |
Output:
Home.js
import React from 'react' import { Button,Table } from 'react-bootstrap' import 'bootstrap/dist/css/bootstrap.min.css' ; import array from './array' ; import { Link, useNavigate } from 'react-router-dom' ; function Home() { let history = useNavigate() // You may skip this part if you're // using react-context api or redux function setID(id,name,age){ localStorage.setItem('id ', id); localStorage.setItem(' Name ', name); localStorage.setItem(' Age ', age); } // Deleted function - functionality // for deleting the entry function deleted(id){ var index = array.map(function(e) { return e.id; }).indexOf(id); // deleting the entry with index array.splice(index,1) // We need to re-render the page for getting // the results so redirect to same page. history(' / ') } return ( <div style={{margin:' 10rem '}}> <Table striped bordered hover size="sm"> <thead> <tr> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> {/* Mapping though every element in the array and showing the data in the form of table */} {array.map((item) => { return( <tr> <td>{item.Name}</td> <td>{item.Age}</td> {/* getting theid,name, and age for storing these value in the jsx with onclick event */} <td><Link to={`/edit`}><Button onClick={(e) => setID(item.id,item.Name,item.Age)} variant="info"> Update</Button></Link></td> {/* Using thr deleted function passing the id of an entry */} <td><Button onClick={e => deleted(item.id)} variant="danger">Delete</Button></td> </tr> )})} </tbody> </Table> {/* Button for redirecting to create page for insertion of values */} <Link className="d-grid gap-2" to=' /create'> <Button variant= "warning" size= "lg" >Create</Button> </Link> </div> ) } export default Home |
Here, I had used localstorage for storing a value and using the values in other pages. You can skip this if you use react-context-api or redux for instance.
Output:
Edit.js
import React, { useEffect, useState } from 'react' import { Button, Form } from 'react-bootstrap' ; import 'bootstrap/dist/css/bootstrap.min.css' ; import array from './array' ; import { Link} from 'react-router-dom' ; import {useNavigate} from 'react-router-dom' ; function Edit() { // Here usestate has been used in order // to set and get values from the jsx const [name, setname] = useState( '' ); const [age, setage] = useState( '' ); const[id,setid] = useState( '' ); // used for navigation with logic in javascript let history = useNavigate() // getting an index of an entry with an id var index = array.map( function (e) { return e.id; }).indexOf(id); // function for handling the edit and // pushing changes of editing/updating const handelSubmit = (e) =>{ e.preventDefault(); // preventing from reload let a = array[index] // getting an index of an array // putting the value from the input textfield and // replacing it from existing for updation a.Name = name a.Age = age // redirecting to main page history( '/' ) } // Useeffect take care that page will be rendered only once useEffect(() => { setname(localStorage.getItem( 'Name' )) setage(localStorage.getItem( 'Age' )) setid(localStorage.getItem( 'id' )) }, []) return ( <div> <Form className= "d-grid gap-2" style={{margin: '15rem' }}> { /* setting a name from the input textfiled */ } <Form.Group className= "mb-3" controlId= "formBasicEmail" > <Form.Control value={name} onChange={e => setname(e.target.value)} type= "text" placeholder= "Enter Name" /> </Form.Group> { /* setting a age from the input textfiled */ } <Form.Group className= "mb-3" controlId= "formBasicPassword" > <Form.Control value={age} onChange={e => setage(e.target.value)} type= "text" placeholder= "Age" /> </Form.Group> { /* Hadinling an onclick event running an edit logic */ } <Button onClick={e => handelSubmit(e)} variant= "primary" type= "submit" size= "lg" > Update </Button> { /* Redirecting to main page after editing */ } <Link className= "d-grid gap-2" to= '/' > <Button variant= "warning" size= "lg" >Home</Button> </Link> </Form> </div> ) } export default Edit |
Output: