Open In App

How to Add an Array Dynamically to React-Bootstrap Table ?

Last Updated : 25 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, We are going to learn how can we dynamically add an array to a react-bootstrap table. While developing the ReactJS applications, we need to do various dynamic things like entering the data in real time. Also, inserting the array data in one go. In react-bootstrap, there is a Table component that is used to display the information in the rows and cols form. We can enter the data in this table through an array in a dynamic way. We need to use the ‘useState’ hook to maintain the state variable which holds the array data. Also, we can use the ‘useRef’ to manipulate the DOM directly. So in this article, we will dynamically add an array to a react-bootstrap table.

Creating React Application and Installing React-Bootstrap

  • Create a React application using the following command:
npx create-react-app array-table
  • After creating your project folder(i.e. array-table), move to it by using the following command:
cd vertical-col
  • Now install react-bootstrap in your working directory i.e. array-table by executing the below command in the VScode terminal:
npm install react-bootstrap bootstrap
  • Now we need to Add Bootstrap CSS to the index.js file:
import 'bootstrap/dist/css/bootstrap.min.css';

Project Structure

Approach 1:

  • We have imported the Table and Button components from the React-Bootstrap library, also we have imported the useState hook from react itself.
  • We have defind the array state variable data that holds the data which will be displayed in the table, then we have arrItem variable which stores the data temporary.
  • When the user enters the element in the input box, the elements are stored in the temporary array.
  • There is another button to Add the Elements in the Table, when the user clicks on that button, all the elements get stored in the array and that array get addded dynamically in the Table.

Example:

 

Javascript




// App.js
import React, { useState } from 'react';
import { Table, Button } from 'react-bootstrap';
import './App.css';
function App() {
    const [data, setData] = useState([]);
    const [arrItem, setArrItem] = useState('');
    const [itemToAdd, setItemToAdd] = useState([]);
    const [srNo, setSrNo] = useState(1);
    const addToArrFunction = () => {
        setItemToAdd([...itemToAdd, { id: srNo, value: arrItem }]);
        setArrItem('');
        setSrNo(srNo + 1);
    };
    const addToTable = () => {
        setData([...data, ...itemToAdd]);
        setItemToAdd([]);
    };
    return (
        <div className="app-container">
            <h1 className="app-title">GeeksforGeeks</h1>
            <h4>Adding Array to Table using useState</h4>
            <Table striped bordered hover className="custom-table">
                <thead>
                    <tr>
                        <th>Sr. No</th>
                        <th>Data in Table</th>
                    </tr>
                </thead>
                <tbody>
                    {data.map((item, index) => (
                        <tr key={index}>
                            <td>{item.id}</td>
                            <td>{item.value}</td>
                        </tr>
                    ))}
                </tbody>
            </Table>
            <input
                type="text"
                value={arrItem}
                onChange={(e) => setArrItem(e.target.value)}
                placeholder="Enter data"
                className="data-input"
            />
            <div className="buttons-container">
                <Button onClick={addToArrFunction} className="add-button">
                    Add to Temp Array
                </Button>
                <Button onClick={addToTable} className="add-button">
                    Add All to Table
                </Button>
            </div>
            <div className="elements-to-add">
                <h3>Elements to Add:</h3>
                <ul>
                    {itemToAdd.map((item, index) => (
                        <li key={index}>{`${item.id}: ${item.value}`}</li>
                    ))}
                </ul>
            </div>
        </div>
    );
}
export default App;


CSS




/* App.css */
  
.app-container {
    text-align: center;
    margin: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
}
  
.app-title {
    color: green;
    font-size: 34px;
    margin-bottom: 10px;
}
  
h3 {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 20px;
}
  
.custom-table {
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
}
  
.data-input {
    width: 100%;
    max-width: 400px;
    padding: 10px;
    margin: 10px;
}
  
.buttons-container {
    display: flex;
    justify-content: center;
}
  
.add-button {
    margin: 10px;
    background-color: #007bff;
    color: #fff;
    border: none;
    padding: 10px 20px;
}
  
.add-button:hover {
    background-color: #0056b3;
}
  
.elements-to-add {
    text-align: left;
    margin-top: 20px;
}
  
ul {
    list-style-type: disc;
}


Steps to Run the File

  • Run the following command in your terminal for the output:
npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Table-1

Approach 2:

  • We have imported the Table as the main component.
  • We have used the useRef hook to create and manage the references of HTML elements in the component.
  • We have used the inputRef and listRef that directly connects or interacts along with the input feild and the table element in the HTML DOM, this allows us the code to acces the properties and values without use of useState hook.
  • User can enter the array elements in the input field separated by the comma. Once the user enters the data, it is been stored in the arr[] object, And then this elements are been added in the Table component.

Example:

Javascript




//App.js
import React, { useRef } from 'react';
import { Table, Button, InputGroup, FormControl } 
    from 'react-bootstrap';
import './App.css';
function App() {
    const inputRef = useRef();
    const listRef = useRef();
    const arr = [];
    let srNo = 1;
    const addTaskFunction = () => {
        const taskText = inputRef.current.value;
        const taskArray = taskText.split(',')
            .map((item) => item.trim());
        if (taskArray.length > 0) {
            taskArray.forEach((taskText) => {
                if (taskText) {
                    arr.push(taskText);
                    const taskRow = document.createElement('tr');
                    taskRow.innerHTML = `
            <td>${srNo}</td>
            <td>${taskText}</td>
            <td>
              <button class="complete-button">Complete</button>
              <button class="remove-button">Remove</button>
            </td>
          `;
                    const completeButton = 
                        taskRow.querySelector('.complete-button');
                    completeButton.addEventListener('click'
                        () => completeTaskFunction(taskRow));
                    const removeButton = 
                        taskRow.querySelector('.remove-button');
                    removeButton.addEventListener('click'
                        () => removeTaskFunction(taskRow));
  
                    listRef.current.appendChild(taskRow);
                    srNo++;
                }
            });
            inputRef.current.value = '';
        }
    };
    const completeTaskFunction = (taskRow) => {
        const completeButton = 
            taskRow.querySelector('.complete-button');
        completeButton.disabled = true;
        taskRow.style.textDecoration = 'line-through';
    };
    const removeTaskFunction = (taskRow) => {
        taskRow.remove();
    };
    return (
        <div className="app-container">
            <h1 className="app-title">GeeksforGeeks</h1>
            <h4>Adding Array to Table using useRef</h4>
            <InputGroup className="mb-3">
                <FormControl
                    placeholder="Add a new task (comma-separated)..."
                    ref={inputRef}
                />
                <Button onClick={addTaskFunction} variant="primary">
                    Add
                </Button>
            </InputGroup>
            <Table striped bordered hover 
                className="custom-table" ref={listRef}>
                <thead>
                    <tr>
                        <th>Sr. No.</th>
                        <th>Task</th>
                        <th>Actions</th>
                    </tr>
                </thead>
            </Table>
            <div className="elements-to-add">
                <h3><center>Task List</center></h3>
            </div>
        </div>
    );
}
export default App;


CSS




/* App.css */
.app-container {
    text-align: center;
    margin: 20px;
}
  
.app-title {
    color: green;
    font-size: 24px;
    margin-bottom: 10px;
}
  
.custom-table {
    width: 80%;
    margin: 20px auto;
    border-collapse: collapse;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
}
  
.custom-table th,
.custom-table td {
    border: 1px solid #ddd;
    padding: 10px;
    text-align: left;
}
  
.custom-table th {
    background-color: #007bff;
    color: white;
}
  
.data-input {
    width: 100%;
    max-width: 400px;
    padding: 10px;
    margin: 10px;
}
  
.buttons-container {
    display: flex;
    justify-content: center;
    margin-top: 10px;
}
  
.add-button {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 10px 20px;
    margin: 0 5px;
    cursor: pointer;
    border-radius: 5px;
    transition: background-color 0.3s;
}
  
.add-button:hover {
    background-color: #0056b3;
}
  
.elements-to-add {
    margin: 20px auto;
    width: 80%;
    text-align: left;
}
  
.complete-button {
    background-color: #4CAF50;
    color: white;
    border: none;
    padding: 5px 10px;
    margin: 0 5px;
    cursor: pointer;
    border-radius: 5px;
    transition: background-color 0.3s;
}
  
.complete-button:hover {
    background-color: #45a049;
}
  
.remove-button {
    background-color: #f44336;
    color: white;
    border: none;
    padding: 5px 10px;
    margin: 0 5px;
    cursor: pointer;
    border-radius: 5px;
    transition: background-color 0.3s;
}
  
.remove-button:hover {
    background-color: #e53935;
}


Steps to Run the File

  • Run the following command in your terminal for the output:
npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Table-2



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads