Skip to content

Instantly share code, notes, and snippets.

@codesnipers
Created July 4, 2023 21:43
Show Gist options
  • Save codesnipers/a57a111f8829747a1e90559fa47fef02 to your computer and use it in GitHub Desktop.
Save codesnipers/a57a111f8829747a1e90559fa47fef02 to your computer and use it in GitHub Desktop.
dynamic table with antd from json
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