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
- 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
- Setting a backgroundImage With React Inline Styles
- Axios Delete request with body and headers?
- How to test a className with the Jest and React testing library
- Add Favicon with React and Webpack
- SyntaxError with Jest and React and importing CSS files
- How to import CSS modules with Typescript, React and Webpack
- How to mock React component methods with jest and enzyme
- How do I wrap a React component that returns multiple table rows and avoid the "<tr> cannot appear as a child of <div>" error?
- How to set up Babel 6 stage 0 with React and Webpack
- Form validation with react and material-ui
- Formatting code with <pre> tag in React and JSX
- React native: How to combine external and inline styles?
- Multiple classNames with CSS Modules and React
- React img tag issue with url and class
- Using onBlur with JSX and React
- Async validation with Formik, Yup and React
- How to create forms with React and Rails?
- React - useRef with TypeScript and functional component
- Proper way to navigate with React Native, Redux, and Navigator
- Test setting text value with React and Enzyme
- How to make react router work with static assets, html5 mode, history API and nested routes?
- Typescript and React setting initial state with empty typed array
- Cannot read property '.then' of undefined when testing async action creators with redux and react
- Is nesting React Context Provider and consuming those with useContext a problem?
- React: how to forward refs to multiple children?
- Update array object in React Redux reducer
- Can TypeScript's `readonly` fully replace Immutable.js?
- How to extends `CSSProperties` in react project
- ReactDOM.unmountComponentAtNode() in Test causes Warning
- Can I set the Recharts axis domain max lower than dataMax?
- React/Redux, how to get user input
- Warning: Failed prop type: The prop `to` is marked as required in `Link`, but its value is `undefined`
- Render unicode characters in react native using variable
- react-router - creating nested routes with no Component nesting
- jest: Mock function have not been called in mock promise function
- How to format the value of a checkbox Field using React Final Form Field Array?
- Using styled components with Typescript, prop does not exist?
- create-react-app with -–template typescript not creating .tsx files
- React Redux unexpected key passed to create store
- Change behavior of Steps React component from Ant Design(https://ant.design/components/steps/)
- Going back from a redirect tag - React Router
- component definition is missing display name on HOC
- How to make owl-carousel responsive in React?
- What is the purpose of export interface Props in React (Typescript ver)