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 go back to the first appearance of state on React
- How do you remove a CSS class from a certain element of a list with React
- How add style for child elements with react-jss component?
- React extract param from url
- Navbar component not loading with react and react-bootstrap
- Not able to pass Data From Nested File Upload React Component to Parent Component
- React - Syntaxerror: unexpected token <
- Managing static files Separately For Media Uploads and Separate for React Build
- Application does not fetch access token from cache using MSAL (react-aad-msal)
- How to display a ref variable without using state in React?
- multi level table row expand collapse react
- Make filter appear from the left to right side
- React JS: Only map certain elements of an array within JSX tag, where the elements to map are iterated
- How do i create duplicates (same keys) in React list?
- React / Redux - Let's say we have two separate lists of Todo Items, completed, and uncompleted
- React - Use enum object values inside switch case rendering
- Stateful value based on Context property not updating
- React-JS change state of a component by pressing on button
- await useFetch and then passing data to another react hook
- React useEffect does not work as expected
- How do I wait for a useReducer dispatch to update the state?
- React does not update values nor state
- SyntaxError in Webpack / React.js Unexpected token = { } in React
- TypeError: Cannot read properties of undefined (reading 'type')
- AWS S3 presigned url with React uploads empty file
- Import System Environment Variable in Javascript
- Warn: State updates from the useState() and useReducer() Hooks don't support the " + ... MERN Stack Application
- rendering data from an array of objects using an onclick
- Updating useState from props
- React useEffect Warning: Maximum update depth exceeded. Is there a way around this?
- How do I convert this class component into function component?
- Express not serving static files correctly for react build
- Two divs scroll simultaneously until one reaches bottom
- How can i update a name field from single element in array of object from a state in reducer in React-Redux?
- React lifecycle with react hooks useEffect
- client rendering react component to html in browser client side with styles
- Using react router with electron
- history.createBrowserHistory is not a function - react js
- Why is my button undefined in my test?
- How can i reset react form all input field?
- How to disable form submit button using availity reactstrap validation
- React Native: TextInput toUpperCase does not work on Android in onChangeText
- react-table iterating over object array to print values in a column
- Typescript extending class to define property className
- this.props.children vs this.props.someName
- Add CSS to react created elements like data-reactroot
- In React Project, how to change and customize node modules
- export 'time' (imported as 'd3') was not found in 'd3'
- Build failed with error MSB4226: The imported project | REACT NATIVE WINDOWS
- Allow textbox only digits and first digit starts with 2 to9
- Redirect to a specific url with different query params using useHistory hook
- BrowserHistory (react-router v4) returns 404 and historyApiFallback not working
- Next.JS getstaticprops revalidate not working
- How to pass in any object for custom hook react
- How to add gulp to reactjs?
- Replace array element (integer) in state
- Redux normalised data using separate reducers
- react-table: unable to interpolate nested json data inside react-table
- (Redux Toolkit) How to access the state outside of the createSlice
- "composes" not working with babel-plugin-react-css-modules
- How to autofocus on the USD value when 3 values are entered in reactjs?
- How to check if a user is logged in and how to save their information? (React)
- Heroku application App crashed can't get path
- While debugging, can I have access to the Redux store from the browser console?
- How to find height and width of div within dialog when set in percent
- Trouble using Redux-Sauce in App? What am I doing wrong?
- why does this react/javascript "removeEventListener" not remove the listener?
- Reactjs : Failed to load module script: WIth MIME type "application/octet-stream" for sharepoint webpart
- Trying to filter an array using checkboxes and useState, checkbox doesn't stay checked
- NextJS useRouter error when used inside function body
- How to lazy load multiple components at a same time
- Which is more efficient: use of many useState hooks or one useState for often updated object?
- Does new React Context API trigger re-renders?
- Material-UI React: Global theme override for Paper component
- How to get current location from react-router?
- Why useEffect is running two times?
- React JS selector with fetch
- send parameters with navigation in react-native
- Both Material-UI radio button are checked
- How to query Sanity blog post with Gatsby
- TypeScript - how should I type these React components?
- Pass state as props from parent to child and then update parent from child onSubmit
- Anchor tag redirects to react spa
- How to access new props.value before render function in React life cycle
- React context returns undefined
- When Reactjs has functional component as parent and child component as class
- styled-components error 'cannot read property of undefined' prop that is being passed
- Fetch api for post not working
- event.target.value is undefined for buttons that wrap an image instead of text
- I need help understanding a TypeError in a React app?
- Adding Heap Analytics code in React Project
- How to I change my react table accesssor value based on data conditionally?
- React Router useLocation() location is not followed to the current page
- Why whenever I type something that does not exist, i got this error?
- Set value in useState after redux dispatch
- I have a TypeError in React and my app won't load because of this error
- Loop an array index inside a map in ReactJS
- Fetch global data for the whole app in Next.js on initial page load
- Duplicate paths in react-route
- GraphQL filter search query returns below error
- Trying to figure out why code won't render list
- Accessing React component params in event handler
- Unmounting a React component the correct way
- Running a child component with a function in parent component
- How to save a list of json data that i get from an API to a class property using fetch
- Why is this.state undefined in this simple React component using a contrived use of bind?
- React: Why is the DIV that I wrap my JSX in suddenly very narrow and not allowing my layout to expand?
- Enzyme/Jest: How to test if mocked function has been called
- Material UI: dialog with Groupbutton
- Debugging live search bar in ReactJS
- reactjs - Import a dynamic file in render() method
- Why is this setState function working abnormally
- How to Format the display of passed props?
- How can i protect routes in my reactjs project?
- ReactJs component showing old data (which is not a list even)
- How to Render Data from API to Table in ReactJS (Function Component)
- React with react-router-dom 4 -- Cannot read property 'params' of undefined
- Displaying a text data while hovering over the image [React Functional Component]
- How do you split page templates into individual components, each querying data?
- Calling an async function inside the if condition of useEffect hook
- Reactjs React.memo doesnt memorized const function
- Private Route React router always redirects to first Route
- React, how to return a value from function to component?
- React component did mount but stated unmounted actually
- How to use imported constant
- Error: Too many re-renders. with useState
- Uncontrolled input of type text to be controlled warning
- include closing tag of a jsx element in another element
- Change Value Properties in Object with Ramda Lenses
- How can I load external images in Next.js?
- Import function into react component and use it in onSubmit
- React/TypeScript/SPFx forEach and map function issues with complex objects
- OnChange event for elements in html set with DangerouslySetInnerHTML in ReactJS
- I want to create a button inside a cell of react-table column
- Make sure Axios/Fetch call runs for at least X Seconds in Javascript
- How can I include a global JS file to my React project using webpack?
- Error when using Maps in react native
- How to focus a input field, which is located in a child component
- Accessing props in onSubmit method of react-dropzone-uploader
- Routing to different tabs in ReactJS
- React ,get 404 when trying to connect localhost to my routs file
- How align Radio group with TextField in Material UI?
- How can I send data from a child component to a parent of a parent of a parent (react)?
- React / Gatsby dynamic background images in a component
- How/where to inject server communication into a Flux workflow?
- Js substring doesn't work on react fetched string
- React js State not being set on forms
- Why is my redux state not updating after dispatch
- Is there a way to show all defined classNames in the Chrome developer tools?
- React Hooks TypeScript inheriting parent state & function types in child
- ref does not work in this reactjs component
- React hooks 'useState()' updater function with axios.post on form submits
- Why Curly braces while handling a Promise object provides undefined data?
- How to fix React app dependencies failing on AWS?
- update state of input type select when select input open or close
- I need load this code before load another code
- Remove Event Listener On Unmount React
- Yup validation to accept more than 0 input digit. Like user can enter 0.001 or 0.0001. But not only 0
- Refactoring a React PureComponent to a hooks based functional component
- Property 'clear' does not exist on type '{}'
- How to mock out a response triggered by a function on the same component in a wrapper?
- react js jest unit testing
- React.js - "this" undefined even after binding
- React | TypeScript - Context of "this" onClick event
- Why wont Axios For Loop allow me to manipulate data in React?
- Can not import image in javascript . Module parse failed: Unexpected character '�' (1:0)
- empty POST request with react/axios
- Why is my Axios fetch giving CORS errors?
- Material dialog showing despite display="none"
- Filter response from api on user search getting error :`Unhandled Rejection (TypeError): Cannot read property 'results' of undefined`