In this tutorial, you will learn how to create a dynamic table that can display any JSON data using React.
How to Create Dynamic Table from JSON Data in React js
Steps to make dynamic table from JSON array of objects:
Step 1 – Create React App
In this step, open terminal and execute the following command on terminal to create a new react app:
npx create-react-app my-react-app
To run the React app, execute the following command on your terminal:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Install Bootstrap
In this step, execute the following command to install react boostrap library into react app:
npm install bootstrap --save
Add bootstrap.min.css file in src/App.js
file:
import "../node_modules/bootstrap/dist/css/bootstrap.min.css"; import DynamicTable from "./dynamic-table/DynamicTable"; function App() { render(){ return ( <DynamicTable /> ); } } export default App;
Step 3 – Create TableData.js File
In this step, create TableData.js file. And add the following code into it:
const TableData=[ {id:1, fullName:"My Name", age:25, city:"Patna"}, {id:2, fullName:"Jani", age:26, city:"Noida"}, {id:3, fullName:"Ravi Singh", age:18, city:"New Delhi"}, {id:4, fullName:"Kumar JI", age:22, city: "Jaipur"}, {id:5, fullName:"Test Kumari", age: 21, city: "Chennai"} ] export default TableData;
The above code uses the fetch API of the browser. It internally uses javascript promises to resolve the asynchronous response.
Step 4 – Create a Dynamic Table Component
In this step, create dynamic table component, which name DynamicTable.js and add the following code into it:
import { useEffect } from "react"; import TableData from "./TableData"; function DynamicTable(){ // get table column const column = Object.keys(TableData[0]); // get table heading data const ThData =()=>{ return column.map((data)=>{ return <th key={data}>{data}</th> }) } // get table row data const tdData =() =>{ return TableData.map((data)=>{ return( <tr> { column.map((v)=>{ return <td>{data[v]}</td> }) } </tr> ) }) } return ( <table className="table"> <thead> <tr>{ThData()}</tr> </thead> <tbody> {tdData()} </tbody> </table> ) } export default DynamicTable;
Step 5 – Start React js App
Execute the following command on terminal to start the React App:
npm start
Then hit the following url on web browser:
http://localhost:3000
Conclusion
In this tutorial, you have learned how to create a dynamic table component in React.js.