I'd love to know how to generate a dynamic table within react, but provide each of my rows of data with proper keys for react to do it's magical stuff.
Here is an example of simple table/row generation I'm doing.
const listItems = (row, index) => (
row.map(item => (
<td key={item + index}>
{item}
</td>
))
);
const listRows = (rows) => {
if (!rows) {
return [];
}
return rows.map((row, index) => {
const key = row[0] + index;
return (
<tr key={key}>
{listItems(row)}
</tr>
);
});
};
const listHeaderItems = (headers) => {
if (!headers) {
return [];
}
return headers.map((item, key) => (
<th key={key}>
{item}
</th>
));
};
The 2 problems with this:
- Using field values as keys, with arbitrary, duplicate and sometimes empty values are subpar as keys. React no likey.
- My solution to problem 1 creates a new problem. Using array index values as keys. This is seen as a no-no from an eslint perspective and considered an anti-pattern because of performance side effects. no-array-index-key , React array index anti pattern
I'd love to help react be more magical with its shadow dom awesomeness, but I'm a little confused on how to achieve this.
In summary: