Created
July 4, 2023 21:43
-
-
Save codesnipers/a57a111f8829747a1e90559fa47fef02 to your computer and use it in GitHub Desktop.
dynamic table with antd from json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from 'react'; | |
import { Table } from 'antd'; | |
// Create the TableComponent | |
const TableComponent: React.FC = () => { | |
const [columns, setColumns] = useState([]); | |
const [data, setData] = useState([]); | |
useEffect(() => { | |
// Fetch the JSON file dynamically | |
fetch('/path/to/dynamicData.json') | |
.then((response) => response.json()) | |
.then((jsonData) => { | |
// Extract columns from the JSON data | |
const dynamicColumns = extractColumns(jsonData); | |
setColumns(dynamicColumns); | |
setData(jsonData); | |
}) | |
.catch((error) => console.error('Error fetching JSON:', error)); | |
}, []); | |
// Helper function to extract columns from the JSON data | |
const extractColumns = (jsonData) => { | |
if (Array.isArray(jsonData) && jsonData.length > 0) { | |
const firstRow = jsonData[0]; | |
return Object.keys(firstRow).map((key) => ({ | |
title: key, | |
dataIndex: key, | |
key, | |
})); | |
} | |
return []; | |
}; | |
return <Table columns={columns} dataSource={data} />; | |
}; | |
export default TableComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment