React JS is a popular and powerful JavaScript library for building user interfaces. It is commonly used for creating dynamic and interactive web applications. One important feature of web applications is the ability to display data in a clear and organized way. In this article, we will discuss how to create a dynamic table in React JS.
Understanding Dynamic Tables
A dynamic table is a table that can change its content based on user input or other events. For example, a dynamic table could display different data based on the user’s selection of a dropdown menu or based on the results of a search query. React JS makes it easy to create dynamic tables that can handle a variety of data and display it in a user-friendly way.
Setting up the Project
Before we start creating the dynamic table, we need to set up a React JS project. Here are the steps to follow:
- Install Node.js and NPM (Node Package Manager) on your computer.
- Open your command prompt or terminal and navigate to the directory where you want to create the project.
- Run the command
npx create-react-app my-table-app
to create a new React JS project named “my-table-app”. - Navigate to the project directory using the command
cd my-table-app
. - Run the command
npm start
to start the development server.
Creating the Table Component
Now that we have set up our React JS project, we can start creating the dynamic table component. Here are the steps to follow:
- Create a new file named “Table.js” in the “src” directory of your project.
- In the “Table.js” file, import the React library and create a new functional component named “Table”.
- Inside the “Table” component, create a state variable to hold the table data. We will use the useState hook to create the state variable. Here is an example:
import React, { useState } from 'react'; function Table() { const [data, setData] = useState([]); return ( // Table component code goes here ); } export default Table;
- Next, we will create a function to fetch the data that we want to display in the table. We will use the useEffect hook to call this function when the component is mounted. Here is an example:
import React, { useState, useEffect } from 'react'; function Table() { const [data, setData] = useState([]); useEffect(() => { async function fetchData() { const response = await fetch('https://api.example.com/data'); const json = await response.json(); setData(json); } fetchData(); }, []); return ( // Table component code goes here ); } export default Table;
In this example, we are using the fetch API to retrieve data from an external API. You can replace the URL with your own API endpoint or use a different method to fetch the data.
- Now we can start creating the table itself. We will use the HTML “table” element and the “map” method to iterate over the data and create table rows. Here is an example:
import React, { useState, useEffect } from 'react'; function Table() { const [data, setData] = useState([]); useEffect(() => { async function fetchData() { const response = await fetch('https://api.example.com/data'); const json = await response.json(); setData(json); } fetchData(); }, []); return ( <table> <thead> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> </tr> </thead> <tbody> {data.map((item, index) => ( <tr key={index}> <td>{item.column1}</td> <td>{item.column2}</td> <td>{item.column3}</td> </tr> ))} </tbody> </table> ); } export default Table;
In this example, we are using the “map” method to iterate over the “data” array and create a new table row for each item. We are also using the “key” prop to assign a unique identifier to each row. Replace “column1”, “column2”, and “column3” with the actual names of your table columns.
- We now have a basic dynamic table component that can fetch data from an external API and display it in a table. However, we can add more functionality to make it even more dynamic and interactive.
Adding Sorting and Filtering
One important feature of dynamic tables is the ability to sort and filter the data based on user input. We can add this functionality to our table component using React JS.
Sorting
To add sorting functionality, we will create a new state variable to hold the current sorting column and direction. We will also create a function to sort the data based on the current sorting column and direction. Here is an example:
import React, { useState, useEffect } from 'react'; function Table() { const [data, setData] = useState([]); const [sortColumn, setSortColumn] = useState(''); const [sortDirection, setSortDirection] = useState('asc'); useEffect(() => { async function fetchData() { const response = await fetch('https://api.example.com/data'); const json = await response.json(); setData(json); } fetchData(); }, []); const sortData = (column) => { const direction = sortColumn === column && sortDirection === 'asc' ? 'desc' : 'asc'; const sortedData = [...data].sort((a, b) => { if (a[column] < b[column]) { return direction === 'asc' ? -1 : 1; } if (a[column] > b[column]) { return direction === 'asc' ? 1 : -1; } return 0; }); setData(sortedData); setSortColumn(column); setSortDirection(direction); }; return ( <table> <thead> <tr> <th onClick={() => sortData('column1')}>Column 1</th> <th onClick={() => sortData('column2')}>Column 2</th> <th onClick={() => sortData('column3')}>Column 3</th> </tr> </thead> <tbody> {data.map((item, index) => ( <tr key={index}> <td>{item.column1}</td> <td>{item.column2}</td> <td>{item.column3}</td> </tr> ))} </tbody> </table> ); } export default Table;
In this example, we are using the “sort” method to sort the “data” array based on the current sorting column and direction. We are also using the “onClick” event to call the “sortData” function when the user clicks on a table header. Replace “column1”, “column2”, and “column3” with the actual names of your table columns.
Filtering
To add filtering functionality, we will create a new state variable to hold the current filter value. We will also create a function to filter the data based on the current filter value. Here is an example:
import React, { useState, useEffect } from 'react'; function Table() { const [data, setData] = useState([]); const [sortColumn, setSortColumn] = useState(''); const [sortDirection, setSortDirection] = useState('asc'); const [filterValue, setFilterValue] = useState(''); useEffect(() => { async function fetchData() { const response = await fetch('https://api.example.com/data'); const json = await response.json(); setData(json); } fetchData(); }, []); const sortData = (column) => { const direction = sortColumn === column && sortDirection === 'asc' ? 'desc' : 'asc'; const sortedData = [...data].sort((a, b) => { if (a[column] < b[column]) { return direction === 'asc' ? -1 : 1; } if (a[column] > b[column]) { return direction === 'asc' ? 1 : -1; } return 0; }); setData(sortedData); setSortColumn(column); setSortDirection(direction); }; const filterData = (value) => { const filteredData = data.filter((item) => { return ( item.column1.toLowerCase().includes(value.toLowerCase()) || item.column2.toLowerCase().includes(value.toLowerCase()) || item.column3.toLowerCase().includes(value.toLowerCase()) ); }); setData(filteredData); setFilterValue(value); }; return ( <div> <input type="text" placeholder="Search..." value={filterValue} onChange={(e) => filterData(e.target.value)} /> <table> <thead> <tr> <th onClick={() => sortData('column1')}>Column 1</th> <th onClick={() => sortData('column2')}>Column 2</th> <th onClick={() => sortData('column3')}>Column 3</th> </tr> </thead> <tbody> {data.map((item, index) => ( <tr key={index}> <td>{item.column1}</td> <td>{item.column2}</td> <td>{item.column3}</td> </tr> ))} </tbody> </table> </div> ); } export default Table;
In this example, we are using the “filter” method to filter the “data” array based on the current filter value. We are also using the “onChange” event to call the “filterData” function when the user types in the search input. Replace “column1”, “column2”, and “column3” with the actual names of your table columns.
Conclusion
In this article, we have learned how to create a dynamic table in React JS. We have covered the basics of fetching data from an external API, creating a table component, and adding sorting and filtering functionality. With this knowledge, you can now create your own dynamic tables in your React JS projects.
FAQ’s
A dynamic table is a table that can be updated with data from an external source and can also be sorted and filtered based on user input.
To fetch data from an external API in React JS, we can use the “fetch” method or libraries like Axios or jQuery.
To add sorting functionality, you can create state variables for the current sort column and sort direction, and use the “sort” method to sort the data array. You can also add event handlers to the table headers to trigger the sorting. See the previous section for a complete example.
To add filtering functionality, you can create a state variable for the current filter value, and use the “filter” method to filter the data array. You can also add an input field for the user to type in the search term, and use the “onChange” event to trigger the filtering. See the previous section for a complete example.
Yes, there are many libraries available that can help you create dynamic tables in React JS, such as React Table, React Bootstrap Table, and Material-UI Table. However, understanding how to create a dynamic table from scratch can give you more flexibility and control over your table.