2

I am new to react. I have a json api which I need to display as a table in client side. I want to use react-table v7. My idea is:

  • Take the keys from the data as column Headers and Accessor
  • The json data are the rows

I have a table component, it takes the headers and data as props, kindly look below:

import React from 'react';
import { useTable } from 'react-table'

const Table = ({
  headers,
  items
}) => {
  function getColumns() {
    if (headers) {
    return headers.map(key => {
      return {

        Header: key.toString(),
        accessor: key.toString()
      };
    });
  }}

const columns = React.useMemo(() => [
    getColumns()
  ],
  []
  )

const data = React.useMemo(() => [
  items
], []
) 

const {
  getTableProps,
  getTableBodyProps,
  headerGroups,
  rows,
  prepareRow,
} = useTable({ columns, data })

return (
  <table {...getTableProps()} style={{ border: 'solid 1px blue' }}>
  <thead>
    {headerGroups.map(headerGroup => (
      <tr {...headerGroup.getHeaderGroupProps()}>
        {headerGroup.headers.map(column => (
          <th
            {...column.getHeaderProps()}
            style={{
              borderBottom: 'solid 3px red',
              background: 'aliceblue',
              color: 'black',
              fontWeight: 'bold',
            }}
          >
            {column.render('Header')}
          </th>
        ))}
      </tr>
    ))}
  </thead>
  <tbody {...getTableBodyProps()}>
    {rows.map(row => {
      prepareRow(row)
      return (
        <tr {...row.getRowProps()}>
          {row.cells.map(cell => {
            return (
              <td
                {...cell.getCellProps()}
                style={{
                  padding: '10px',
                  border: 'solid 1px gray',
                  background: 'papayawhip',
                }}
              >
                {cell.render('Cell')}
              </td>
            )
          })}
        </tr>
      )
    })}
  </tbody>
</table>
  )
}



export default Table;

Then I have another component to make get request via axios and set columns and data from its response and import the Table component to pass the props define here, code below:

import React, { useEffect, useState } from 'react'
import Table from './Table'
import axios from 'axios'


export const STable = () => {

const [columns, setColumns] = useState([])
const [rows, setRows] = useState([])

const getData = () => {
    axios.get("http://localhost:5001/")
    .then(res => {
        console.log(res.data)
        setColumns({ columns: Object.keys(res.data[0]) })
        setRows({ rows: res.data })
    })
    .catch(error => {
        console.log(error)
    })
}

useEffect(() => {
    getData()
}, [] )

return (
    <div>
        <Table headers={columns} items={rows} />
    </div>
)
}

export default Stable;

Finally the App component

import React from 'react';
import STable from './components/STable';


function App() {
return (
<div>
  
  <STable/>
</div>

 );
}

export default App;

However I get this error, see pic,

enter image description here

I do not know where I am doing wrong. I would appreciate any help.

1 Answer 1

0

You need to have id field in all columns with accessors. In your code you need to set id field for every inner column like that.

return headers.map(key => {
      return {
        id: key toString(),
        Header: key.toString(),
        accessor: key.toString()
      };
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Thanks for your answer, I already tried the same and it didn't work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.