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.
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.
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.
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>
}