How to render a dynamic table in React Js

Last updated : Jul 30, 2023 12:00 AM

An HTML table is an array of table rows or tr's. A table tr is an array of table data cells, or td's. Therefore I can represent an HTML in Typescript like the one below.

Table interfaceDescription
interface Tr {
    td: string[]
}
interface Table {
    tr: Tr[]
}

I can render a table with dynamic rows and columns with the above hierarchy. Of course, each table row must have an equal number of table cells to table to be syntactically valid.

Here is how to create a table JSON using the structure I described above.

Table dataDescription
const table: Tr[] =
  [
    { td: ['Oklahoma', 'Texas', 'Missouri', 'New York'] },
    { td: ['California', 'Oregon', 'Seattle', 'Georgia'] },
    { td: ['Arkansas', 'Illinois', 'Florida', 'Tennessee'] },
    { td: ['Massachusetts', 'Connecticut', 'Montana', 'Delaware'] },
    { td: ['Arizona', 'Nevada', 'Louisiana', 'New Mexico'] }
  ]

Note that I define the table variable as an array of Tr's. That way, I can eliminate the unnecessary Table interface.

Finally, the complete code that does everything.

Render tableDescription
export interface Tr {
    td: string[]
}

const table: Tr[] =
  [
    { td: ['Oklahoma', 'Texas', 'Missouri', 'New York'] },
    { td: ['California', 'Oregon', 'Seattle', 'Georgia'] },
    { td: ['Arkansas', 'Illinois', 'Florida', 'Tennessee'] },
    { td: ['Massachusetts', 'Connecticut', 'Montana', 'Delaware'] },
    { td: ['Arizona', 'Nevada', 'Louisiana', 'New Mexico'] }
  ]

export const ZeebraTable = () => {
   return <table>
      {table.map((tr: Tr, index) => {
         return <tr key={index}>
            {tr.td.map((td, index) => {
               return <td key={index}>{td}</td>
            })}
         </tr>
      })}
   </table>
}
Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...