Delete Multiple Table Rows from Server using React

Introduction

In this tutorial we are going to show how to delete multiple table rows from server using React JS.

Let’s say we have product data which got displayed on HTML table on user interface (UI). And users want to either select individual row or multiple rows for deletion from the HTML table. Therefore we will put individual checkbox against each row on the table for multiple rows selection. Once user selects the rows, he/she may click on a button to delete the selected products.

We determine the each row’s css class name dynamically to apply two distinct colors according to a row is odd or even. So we are highlighting the odd and even rows of the HTML table using different color to increase the visibility of the rows.

Clicking on the delete button will delete the selected rows from the HTML table as well as from the server side.

The deletion of rows from the HTML table will not reflect the changes on UI (user interface) untill you refresh the page. If you want to reflect the changes on UI right away, then you need to redirect the home page right after deleting the rows.

Let’s create the working example.

Prerequisites

React JS, NodeJS, CSS, HTML

REST API Endpoints – /products and /delete/products

How to create React JS project in Windows

Once your React project is created we will edit two files App.js and App.css under src folder.

Fetch and Display Products

First we will fetch product details from server side and display on UI (User Interface).

Inside the constructor of the App class we declare two state variables:

constructor(props) {
   ...
   this.state = {products: []};
   this.headers = [
	{ key: 'id', label: 'Id'},
	{ key: 'name', label: 'Name' },
	{ key: 'code', label: 'Code' },
	{ key: 'price', label: 'Price' }
   ];
}

The first state variable products holds the product details fetched from server and the second variable displays the HTML table header on UI.

We use componentDidMount() to fetch the data from server side.

componentDidMount() {
	fetch('http://localhost:8080/products')
		.then(response => {
			return response.json();
		}).then(result => {
			//console.log(result);
			this.setState({
				products:result
			});				
		});
}

Here is the render() function that finally renders the UI with product details on HTML table.

render() {
	const productFound = this.state.products && this.state.products.length;
	if(productFound) {
		return (
			<div id="container">
				<div id="msg"></div>
				<button type="button" onClick={this.deleteProducts}>Delete Selected Product(s)</button>
				<table className="datatable">
					<thead>
						<tr>
							{
								this.headers.map(function(h) {
									return (
										<th key={h.key}>{h.label}</th>
									)
								})
							}
						</tr>
					</thead>
					<tbody>
						{
							this.state.products.map(function(item, index) {
							return (
								<tr key={index} className={(index % 2) ? "odd_col" : "even_col"}>
								  <td><input type="checkbox" className="selectsingle" value="{item.id}" checked={this.state.checkedBoxes.find((p) => p.id === item.id)} onChange={(e) => this.toggleCheckbox(e, item)}/>
								  &nbsp;&nbsp;{item.id}
								  </td>
								  <td>{item.name}</td>
								  <td>{item.code}</td>
								  <td>{item.price}</td>
								</tr>
							)}.bind(this))
						}
					</tbody>
				</table>
			</div>
		)
	} else {
		return (
			<div id="container">
				No product found
			</div>
		)
	}
}

Notice we have identified odd or even row and accordingly we added odd_col or even_col to apply two different colors on rows.

We have put a checkbox against each row to either select or deselect the checkbox for deleting or not deleting.

We have put a button on top of the HTML table to delete the selected rows on HTML table. Clicking on this button will delete products from HTML table as well as server side.

Remember the changes on UI will not be reflected until you refresh the page.

Toggle Checkbox

Now we will see the functionality of toggleCheckBox() function.

As we are going to either select/deselect or check/uncheck checkbox so we need two things – a state variable to keep track of checkboxes which are checked and another variable to bind this function.

We add the following two lines inside constructor in addition to the previous state variables.

this.state = { checkedBoxes: []	};
this.toggleCheckbox = this.toggleCheckbox.bind(this);

Here is the definition of the toggleCheckBox():

toggleCheckbox = (e, item) => {		
	if(e.target.checked) {
		let arr = this.state.checkedBoxes;
		arr.push(item.id);
		
		this.setState = { checkedBoxes: arr};
	} else {			
		let items = this.state.checkedBoxes.splice(this.state.checkedBoxes.indexOf(item.id), 1);
		
		this.setState = {
			checkedBoxes: items
		}
	}		
	//console.log(this.state.checkedBoxes);
}

In the above function we push item into or pop item from the checkedBoxes according to whether a particular checkbox was checked or not.

Delete Products

Once we select the desired checkboxes for products on HTML table we can delete the selected products by clicking the button.

On clicking the button the REST endpoint /delete/products is called and the selected products get deleted from the server.

We need to bind deleteProducts() function inside the constructor.

this.deleteProducts = this.deleteProducts.bind(this);

The deleteProducts() function is given below:

deleteProducts = () => {
	if(window.confirm('Are you sure, want to delete the selected product?')) {
		fetch('http://localhost:8080/delete/products', {
			method: 'POST',
			body: JSON.stringify({'ids' : this.state.checkedBoxes}),
			headers: {'Content-Type' : 'application/json; charset=UTF-8'}
		}).then(response => {
				if(response.status === 200) {
					document.getElementById('msg').innerHTML = '<span style="color:green;">Products deleted successfully</span>';
				}
			})
	}
}

We have also put a div with id=”msg” to display either success or error message.

Apply Style

We apply some basic style on HTML table.

table.datatable {
	width:100%;
	border: none;
	background:#fff;
}
table.datatable td.table_foot {
	border: none;
	background: #fff;
	text-align: center;
}
table.datatable tr.odd_col {
	background: none;
}
table.datatable tr.even_col {
	background: #ddd;
}
table.datatable td {
	font-size:10pt;
	padding:5px 10px;
	text-align: left;
}
table.datatable th {
	text-align: left;
	font-size: 8pt;
	padding: 10px 10px 7px;   
	text-transform: uppercase;
	color: #fff;
	background-color: black;
	font-family: sans-serif;
}

Testing the Application

Make sure your server application is up and running. Next is to run the React JS application by executing command npm start in the command line tool on project’s root directory.

The following youtube video shows the result of the application.

Source Code

Download

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *