Using CRUD operations, we manage the data flow between the client and the server.So, in this post, we’ll learn how to perform CRUD operations with inline table editing with edit icon and delete in react js using rest API.
Sometimes in our application, we need to perform insert, update and delete records operation in a Table using inline editing.
In our last article, we discussed crud operation in react js using rest api. In this post, We will discuses add edit records using table and bootstrap and icons.
Suppose we have one page in which we can see the list of staff in our company and we want to perform the crud operation instead of creating 4 components to perform these tasks we can create a single component to fulfill our requirements. So in this article, we will perform add, edit and delete rows of an HTML table with the help of bootstrap and font awesome icon.

We are using free rest API for showing the demo
- GET http://restapi.adequateshop.com/api/Tourist
- POST http://restapi.adequateshop.com/api/Tourist
- PUT http://restapi.adequateshop.com/api/Tourist/15863
- DELETE http://restapi.adequateshop.com/api/Tourist/15863
If you want to read more about RESTful APIs – You can refer to the below link here we have given a sample rest API for testing purposes.
Add action icons (edit, delete) in table using React,js
- Create react js app using the below command
npx create-react-app crud-app
- Install bootstrap CSS and font-awesome in our project using the below command
npm install bootstrap –save
npm install –save font-awesome
Create two folders called “httphelpers” and components in the src folder.
Inside httphelpers create one file restHelper.js and inside the components folder, create three files i.e Touristtable.js, Crudtourists.js, and Addtourist.js.
restHelper.js is a file that contains commonly used functions with static type. The benefit of creating such a helper class is that we can write all common functions in a single place file and can re-use them in any component so using a helper file, we can maintain code re-usability and maintainability.
restHelper.js
export const restHelper = () => {
const callAPI = async (endpointurl, options = {}) => {
const defaultHTTPMethod = "GET"
const defaultHTTPHeaders = { //set defaultHeaders of Http request
"Content-Type": "application/json",
Accept: "application/json",
}
const controller = new AbortController() //using AbortController to cancel ongoing fetch requests
options.signal = controller.signal
options.method = options.method || defaultHTTPMethod
options.headers = options.headers
? { ...defaultHTTPHeaders, ...options.headers }
: defaultHTTPHeaders
options.body = JSON.stringify(options.body) || false
if (!options.body) delete options.body
setTimeout(() => { // cancel request if it will take more then 5s
controller.abort()
}, 5000)
try {
const apiResponse = await fetch(endpointurl, options)
return await apiResponse.json()
} catch (err) {
return err
}
}
//calling get API For fetching data
const get = (endpointurl, options = {}) => callAPI(endpointurl, options)
//Post to insert
const postCreate = (endpointurl, options) => {
options.method = "POST"
return callAPI(endpointurl, options)
}
//Put Api calling
const putUpdate = (endpointurl, options) => {
options.method = "PUT"
return callAPI(endpointurl, options)
}
//Delete Api calling
const deletedata = (endpointurl, options) => {
options.method = "DELETE"
return callAPI(endpointurl, options)
}
return {
get,
postCreate,
putUpdate,
deletedata,
}
}
Touristtable.js
import React from "react"
import Form from "./Addtourist"
import 'bootstrap/dist/css/bootstrap.min.css';
import 'font-awesome/css/font-awesome.min.css';
const Touristtable = ({ tourists, postTourist, updateTourist, deleteTourist }) => {
debugger;
const showUpdateUser = id => {
const form = document.getElementsByClassName(`show-form-${id}`)
form[0].classList.toggle("hide-form")
}
const Row = ({ tourist }) => {
return (
<>
<tr>
<td>{tourist.tourist_name}</td>
<td>{tourist.tourist_email}</td>
<td>{tourist.tourist_location}</td>
<td>
<i className="fa fa-pencil-square fa-2x text-info" onClick={() => showUpdateUser(tourist.id)}></i>
<i className="fa fa-trash fa-2x text-danger" onClick={() => deleteTourist(tourist.id)}></i>
</td>
</tr>
<tr className={`hide-form show-form-${tourist.id}`}>
<Form userData={tourist} postTourist={postTourist} updateTourist={updateTourist} showUpdateUser={showUpdateUser} />
</tr>
</>
)
}
return (
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Location</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{tourists && tourists.map(u => <Row tourist={u} key={u.id} />)}
</tbody>
</table>
)
}
export default Touristtable
Addtourist.js
import React, { useState } from "react"
import 'font-awesome/css/font-awesome.min.css';
import { faL } from "@fortawesome/free-solid-svg-icons";
const Addtourist = ({ userData = {}, postUser, updateTourist,showUpdateUser }) => {
const [user, setUser] = useState({
id: userData.id ?? 0,
tourist_name: userData.tourist_name ?? "",
tourist_email: userData.tourist_email ?? "",
tourist_location: userData.tourist_location ?? "",
})
const handleValue = e => {
setUser({ ...user, [e.target.name]: e.target.value })
}
const submitUser = e => {
e.preventDefault()
debugger;
if (user.tourist_name === "" || user.tourist_email === "" || user.tourist_location === "") return
if (userData.id) {
debugger;
updateTourist(userData.id, user)
} else {
postUser(user)
}
setUser({ ...user, "tourist_name": "", "tourist_email": "", "tourist_location": "" })
}
const hiderow = e => {
showUpdateUser(userData.id);
}
const isAdd = !userData.id ? true : false;
return (
<>
<td>
<input
type='text'
name='tourist_name'
className="form-control"
value={user.tourist_name}
placeholder='Name'
onChange={e => handleValue(e)}
/>
</td>
<td>
<input
type='email'
name='tourist_email'
className="form-control"
value={user.tourist_email}
placeholder='Email'
onChange={e => handleValue(e)}
/>
</td>
<td>
<input
type='text'
name='tourist_location'
className="form-control"
value={user.tourist_location}
placeholder='location..'
onChange={e => handleValue(e)}
/>
</td>
<td>
{isAdd ?
<input
className='btn btn-primary btnsubmit'
type='submit'
value={`${!userData.id ? "Add new user" : "Save user"}`}
onClick={submitUser}
/> :
<i className="fa fa-check fa-2x text-success" onClick={submitUser}></i>
}
{isAdd ? "" : <i className="fa fa-times fa-2x text-muted" onClick={hiderow}></i>}
</td>
</>
)
}
export default Addtourist
Crudtourists.js
import React, { useState, useEffect } from "react"
import Form from "./Addtourist"
import Tablelist from "./Touristtable"
import 'bootstrap/dist/css/bootstrap.min.css';
import { restHelper } from "../httphelpers/restHelper"
const Crudtourists = () => {
const [tourists, settourists] = useState(null)
const url = "http://restapi.adequateshop.com/api/Tourist"
const api = restHelper()
useEffect(() => {
gettourists()
}, [])
const postTourist = tourist => {
api
.postCreate(`${url}`, { body: tourist })
.then(res => gettourists())
.catch(err => console.log(err))
}
const updateTourist = (id, tourist) => {
api
.putUpdate(`${url}/${id}`, { body: tourist })
.then(res => gettourists())
.catch(err => console.log(err))
}
const deleteTourist = id => {
api
.deletedata(`${url}/${id}`, {})
.then(res => gettourists())
.catch(err => console.log(err))
}
const gettourists = () => {
api
.get(`${url}`)
.then(res => {
if(res && res.data)
{
settourists(res.data)
}
})
.catch(err => console.log(err))
}
if (!tourists) return null
return (
<>
<h3>Add New Record</h3>
<table>
<tbody>
<tr>
<Form postUser={postTourist} />
</tr>
</tbody>
</table>
<div className='container-fluid'>
<h3>All Tourist</h3>
<Tablelist
tourists={tourists}
settourists={settourists}
postTourist={postTourist}
updateTourist={updateTourist}
deleteTourist={deleteTourist}
/>
</div>
</>
)
}
export default Crudtourists
App.js
import logo from './logo.svg';
import './App.css';
import CrudData from "./components/Crudtourists"
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
return (
<div className="container-fluid">
<main>
<CrudData />
</main>
</div>
);
}
export default App;
I’m assuming that you are familiar with React Js framework and creating React Js applications. If not then please go through the following articles:
The post React Js- Fetch data from API using hooks appeared first on Software Development | Programming Tutorials.
Read More Articles
- How to edit react bootstrap table and save data after editing
- How to hide a column on REACT Material table in all rows and show it on Edit for the Particular Row I am editing and Add Operations on new row adding?
- Edit and Delete React Bootstrap table rows
- React Material Table action OnClick event for edit and delete does not fire action
- Closing React Semantic UI modal with button and close icon
- React table dynamic page size but with size limit and pagination
- React component with Edit Mode and View Mode, is this a correct pattern?
- React Native: Text and Icon inline
- TypeError: Object(...) is not a function with React Table and moment.js
- wp-json API returns 401 on post edit with React and nonce
- React Convert Div and Table Component Into PDF With Multiple Pages and CSS
- lodash , convert string from svg circle (properties and values separates with space) to object for spread in react component inline
- Header flickering and freezing issue with material table (implemented with react window + react window infinite loader)
- Not able to add, update, delete rows in material table react using class based component. Previously it was working with functional component
- React inline style with const and "text"
- Test an whole table React component cells with jest and Enzyme
- Problem to delete a row from a table with React
- Trouble with defaultSorted and React Bootstrap table Next
- React make table clickable and edit details
- Reordering table columns with react via drag and drop
- Sorting React table by clicking table headers for columns with numerical and string values
- How do i delete a specific item by it's id with react and the fetch method
- React table with sorting and pagination doesn't update
- Update a Table with React Hooks when a Row is Added, Deleted and Modified? [Issue: Gets Before Post and Delete]
- Repeating Edit and Delete Button in React via Mui Datatable
- Problem unit testing a delete method with mock service worker (MSW), node and React
- How to create a dynamic, custom React Table Component with action and status buttons
- table's both column and row reordering , drag and drop also edit the table cell in react js
- How to use delete request with axios in react project and Firebase?
- REACTJs: How to change color and size of edit and delete icon in Material-Table?
- how to write if statement in fixed password value in react yup
- React: Function components cannot be given refs when displaying a modal
- setting style values dynamically - react
- Update all Object Elements of a State Array with React Hooks
- How can I render a list of search results?
- filtering through an array of JSON objects by UI
- Destructuring values from object of the first index of array
- Select form field not populating with options from state in ReactJS
- Closure value changes without being reset
- How to map and filter through array based on a value?
- How do I interpret the following error I've received?
- React search and filter methods issue
- Side panel with components loading dynamically based on context
- Running React & Express in Docker without exposing multiple Ports
- What makes object from react state is undefined but accessible in console?
- useCallback Hooks getting old state values and not updating
- How to test the antd Dropdown with Enzyme
- How to build a "pure" web browser application client for Aws Chime?
- How do i add functionality to my nav dots in my image slider?
- "Objects are not valid as a React child" and linters
- Accessing event trigger button onclick function
- the initialstate for use reducer isn't updating while using context api in react js
- Split a string into sub-strings starting from " ] " ending with "As"
- How to display a parent container on the main Router
- I keep getting an invalid hook call error
- React: Wait until all assets are loaded
- How to get the value of custom atttributes in react hooks?
- Show or Hide on div among multiple divs React
- React/webpack - How can I host react app on one server and images/fonts on another server?
- React - toggle only one button, not all
- Setting same value using set function in Record is creating a new object
- Reset the store to it's initial state on receiving a specific action
- Test for disappearance of element times out
- Links to external resource are empty in React
- How to make React Leaflet Marker popup in right side always?
- React-Router/Redux - Dynamic Isomorphic Routes
- Unable to override the `onChange` handler of formik Select
- bootstrap-datepicker with React: onChange doesn't fire while onClick does
- React Redux sync action returns some Proxy object instead of string
- Dynamically generating JSX in React
- React JS - Marking Importance/Priority of Img Loading
- the onload is not working on my react page
- Wrong ID gets passed from delete item Mutation
- Babel throws a syntax error on arrow function
- How can I add automatic decreasing time zone in my react.js program?
- How can I integrate searching functionality on table?
- module.exports not available on dependency (import)
- Passing ID in component
- How to add transitions to a react scroll event
- How to draw connecting lines between web elements on a page
- Can't call setState on a component that is not yet mounted, even though it is?
- How can I render my popup component over a Container or Div instead of below to it
- Error server Error: Actions must be plain objects. Use custom middleware for async actions
- Passing Boolean State from one component to another component React.JS
- this.setState does not update state
- Adding types to async func inside createAsyncThunk
- React JSX add min date time to datetime-local input
- Remove console.logs with Webpack & Uglify
- Can not read properties of null (reading '0'). React
- Cannot find name in Typescript with MobX
- Change styling of react components created during render?
- I am using socketio with react as the frontend and node with express js to make an app
- How can i modifier a state only when has the same ID
- How to use React component in Angular 6 application
- Why can't I use nested yield in for..in loop in Redux-Saga
- react-pdf utf8 font not working when on-fly-rendering, but works fine when render
- How to refactor the if else code using typescript and react?
- How to ı use function for the only localstorage events, without component?
- React JS: map() not working for object of arrays
- How to dispatch an action from select
- ReactJS hooks: update state inside condition
- How to toggle ON-/OFF button which Fetch data from API?
- React Private Routing through id
- Is it possible to get the name of a nested, inner React Component by calling a function from one of its props?
- Clear the form field after submitting the form using ReduxForm in ReactJS
- How can I wait for multiple promises to all be done before using their return data for another function call?
- React: how using with axios 'withCredentials'
- Prevent re-render using React.memo and React.useCallback
- How to add className to Ant Design Mobile Dialog footer button?
- setState while looping through an array of props - React ComponentDidUpdate
- ERR_NAME_NOT_RESOLVED using Docker network to communicate between a backend container and a React container
- Transition page content excluding the header and footer
- Error: Cannot find module './img.jpg' on react.js
- How to iterate through a map in React JS
- Cntrl S to submit a from in react JS but input field not working
- input field values not not what expected
- React Draggable - How to remove border?
- GridToolbarExport from Material UI stop to work after last version? 5.0.0-alpha.37
- React - Passing State to child component
- Change background color to gradient in react-chartjs-2
- What is ACTUALLY the right way to transition/redirect using React Router?
- Check if item already exists in cart when adding REACT
- How to fetch elements in which object array exist
- ReactJs: render a collection of dynamic components
- How to customize the style in react-datepicker?
- Javascript array equality control and changing value
- How can I make state updating asynchronous in React+Redux
- React useState not updating the states on submit form
- Customize card background with react-bootstrap
- How to force a "pedantic" like errors about always setting types?
- Get every product image url
- Dog API breeds return undefined 404 error React.js
- Do nested Suspense components cause a sequential or a parallel load?
- Redirecting using React Router shows blank page
- How do I have 2 onClick action on javascript?
- Uncaught TypeError: can't define property "x": Object is not extensible
- Toggle variable upon onClick in JSX
- How do I update URL parameters and call fetch while on the same page with React?
- ReactJS, import files within render()
- Why does eval() not work for imported functions?
- React - How do I handle checkbox data correctly
- load json with reactjs
- Redirect to login page using react-router v4
- How to get data from document in a parent collection based on a query in a subcollection
- How to pass onChange and props in a function
- MUI: How to prevent Grid items from going on next row?
- Dynamic key in immutability update helper for array
- Firebase signInWithPopup() function, pop-up google sign in Window but the pop-up does not show any google accounts
- Error with Gatsby plugin Gatsby-Source-Wordpress
- Looking for patterns to work with Timezones and dates Front-end(React) and Backend(nodejs)
- How to decode JWT token by using jwt-decode library in reactjs
- ReactJs reset interval timer in repeat
- Configure Mocha to look for `.jsx`/`.es6` files
- How do you return function results to a React Component?
- how to add background color only for actived item in a <li> using styled component?
- How can I create an audio progress bar in React?
- How to check if a create-react-app project has been ejected or not?
- How to manage state through Context and typescript
- ”Wasted time" shown by React.addons.Perf.printWasted
- react vs react DOM confusion
- add a className for every 12th item in array skipping first 14 items and last 14 items?
- Using aria attributes on elements in react
- React setState() needs 2 clicks to update UI
- Creating dynamic array in react js
- Apply changes according to div id
- How to avoid unnecessary render in React using Hooks API
- React JS - Expected `onClick` listener to be a function, instead got a value of `string` type
- Find "component" in plain text using regex and plain javascript
- react-router only goes to index route
- React + TS: How to get all children heights?
- How to do a simple post request on react given an api
- Select props in Textfield material-ui
- How can I access props from inside a component
- Is componentDidMount of parent called after all componentDidMount of children?
- How to validate each character in firstName with yup?
- How do i pass the props to another component via react router?
- Regex validation within if statements
- How to correctly bind React onClick event with Redux?
- Showing the error "cannot find the module 'undefined'" when iam trying to give the location of image using props
- In ReactJS trying to get params but I get property 'id' does not exist on type '{}'
- How to add React components based on conditional statements evaluating a boolean based on a changable counter
- Is there a way to reuse a reducer logic in redux?
- Use create-react-app with php
- React-Router + React Hooks using withRouter
- Array.push is empty outside while loop
- mapStateToProps not getting called at all
- Resize SVG component to fit parent
- How to output php code block in reactjs?
- fetching data in Next.js
- React admin custom input component with text input base style
- TypeError: Cannot read property 'map' of undefined in react.js
- How to get a React Project running in Docker?
- How to get X-Total-Count header with RTK Query?
- why am I getting Unexpected token error in React js project?
- How to fix the data.map not a function api
- React testing library: how to getByRole on custom role
- nginx configuration to provide dynamic error pages
- How to get searched word or params in URL
- react-native pass state globally using redux
- How to pass value from functional child component to class parent component and save value to state?