Hello friends, welcome back to my blog. Today in this blog post, I am going to show you, Reactjs Add Delete Row on Button Click Using UseState Hook.
Guys in this post we will below things:
- React js useState hook.
- We will add and delete table rows dynamically.
- useState is a Hook that allows you to have state variables in functional components
For reactjs new comers, please check the below link:
Friends now I proceed onwards and here is the working code snippet and please use this carefully to avoid the mistakes:
1. Firstly, we need fresh reactjs setup and for that, we need to run below commands into out terminal and also we should have latest node version installed on our system:
npx create-react-app reacthooks cd reacthooks npm start
2. (Optional, I have used for better looks of table)Now we need to run below commands into our project terminal to get bootstrap and related modules into our reactjs application:
npm install bootstrap --save npm start //For start project again
3. Finally for the main output, we need to add below code into our reacthooks/src/App.js file or if you have fresh setup then you can replace reacthooks/src/App.js file code with below code:
import React, { useState } from "react";
import './App.css';
//Bootstrap
import 'bootstrap/dist/css/bootstrap.min.css';
export default function App() {
//use of hook for couting
const [noOfRows, setNoOfRows] = useState(1);
return (
<div className="app container p-5">
<h1 className="p-5">Reactjs Add Delete Row on Button Click Using UseState Hook</h1>
<table class="table table-hover table-bordered p-5">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
{[...Array(noOfRows)].map((elementInArray, index) => {
return (
<tr>
<th scope="row">{index}</th>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
);
})}
</tbody>
</table>
<button type="button" class="btn btn-primary me-3" onClick={() => setNoOfRows(noOfRows + 1)}>Add</button>
<button type="button" class="btn btn-danger" onClick={() => setNoOfRows(noOfRows - 1)}>Delete</button>
</div>
);
}
Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.
Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements.
I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.
Jassa
Thanks


How to delete a specific row?
This functionality is working.
if i have 5 rows and i want to delete 3rd row only. how i can do that?