komarovalexander / ka-table

Lightweight MIT React Table component with Sorting, Filtering, Grouping, Virtualization, Editing and many more
http://ka-table.com
MIT License
769 stars 56 forks source link

Setting columns dynamically #345

Closed chanakyabhardwajj closed 1 year ago

chanakyabhardwajj commented 1 year ago

Great work on this library! Thanks for your work!

I wanted to ask if it is possible to use it when the columns are not known beforehand. For example, if I want to parse a CSV file and render it as a table, how can I do that?

The column names are usually the first row of the CSV file followed by the data. I am able to parse the CSV file and store the columns and the rows in a Context. But when I try to render it, it just renders an empty box. No columns or rows.

My setup is like this:

App.tsx looks like:

// `ctxValue` contains `firstRow` & `tableData` 
<AppContext.Provider value={ctxValue}>
  <MyTable />
</AppContext.Provider>

And my MyTable.tsx looks like:

import 'ka-table/style.css'

import React, { useContext, useState } from 'react'
import { AppContext } from '../appContext'
import { DataType, Table } from 'ka-table'
import { Column } from 'ka-table/models'

const MyTable: React.FC = () => {
  const context = useContext(AppContext)
  const columns =
    context?.firstRow.map((colName) => {
      return {
        key: colName,
        title: colName,
        dataType: DataType.String
      }
    }) || []

  const [tableProps, changeTableProps] = useState({
    data: context?.tableData,
    rowKeyField: 'id',
    columns: columns
  })

  return (
    <Table
      {...tableProps}
    />
  )
}

export default MyTable

However, this does not render anything. I just see an empty box like this:

Image

All the demos, assume the columns are known beforehand e.g. this json demo. Is there an example of loading dynamic data where the columns are not known earlier?

I would really appreciate your help here! Thanks!

chanakyabhardwajj commented 1 year ago

Never mind, I figured it out. I was not re-rendering the table correctly.