I have a React component that generates a table based on an array of objects, which gets populated with data in an object.
I'm trying to learn as much as I can about React.js / JavaScript. Could anyone with more experience in this area show me a way to simplify the code that I have here? Or if there are any other 'fancy' ways of doing what is being done in the code?
App.js
import React, { Component } from 'react';
import Table from './Table';
//Columns defines table headings and properties to be placed into the body
let columns = [
{
heading: 'Name',
property: 'name'
},
{
heading: 'Age',
property: 'age'
},
{
heading: 'Sex',
property: 'sex'
},
{
heading: 'Breed',
property: 'breed'
},
]
//Data is the array of objects to be placed into the table
let data = [
{
name: 'Sabrina',
age: '6',
sex: 'Female',
breed: 'Staffordshire'
},
{
name: 'Max',
age: '2',
sex: 'Male',
breed: 'Boxer'
}
]
class App extends Component {
render() {
return (
<>
<Table
columns={columns}
data={data}
propertyAsKey='name' //The data property to be used as a key
/>
</>
);
}
}
export default App;
Table.js
import React, { Component } from 'react';
class Table extends Component {
buildTable = (columns, data, key) => {
let headerRow = [];
let dataRows = [];
//Build the table header
columns.forEach (col => {
headerRow.push(
<th key={`header-${col.heading}`}>{col.heading}</th>
);
});
//Build the rows
data.forEach(item => {
let dataCells = [];
//Build cells for this row
columns.forEach (col => {
dataCells.push(
<td key={`${item[key]}-${col.property}`}>{item[col.property]}</td>
);
});
//Push out row
dataRows.push(
<tr key={`${item[key]}-row`}>{dataCells}</tr>
)
});
return(
<>
<thead>
<tr>{headerRow}</tr>
</thead>
<tbody>
{dataRows}
</tbody>
</>
);
};
render() {
const {
columns,
data,
propertyAsKey
} = this.props;
return (
<table className='table'>
{this.buildTable(columns, data, propertyAsKey)}
</table>
);
}
}
export default Table;