diff --git a/snippets/MappedTable.md b/snippets/MappedTable.md new file mode 100644 index 000000000..67c5d0377 --- /dev/null +++ b/snippets/MappedTable.md @@ -0,0 +1,48 @@ +### MappedTable + +Renders a table with rows dynamically created from an array of objects and a list of property names. + +Use `Object.keys()`, `Array.prototype.filter()`, `Array.prototype.includes()` and `Array.prototype.reduce()` to produce a `filteredData` array, containing all objects with the keys specified in `propertyNames`. +Render a `` element with a set of columns equal to the amount of values in `propertyNames`. +Use `Array.prototype.map` to render each value in the `propertyNames` array as a `` element, containing a `
` element. +Use `Array.prototype.map` to render each object in the `filteredData` array as a `
` for each key in the object. + +```jsx +function MappedTable({ data, propertyNames }) { + let filteredData = data.map(v => + Object.keys(v) + .filter(k => propertyNames.includes(k)) + .reduce((acc, key) => ((acc[key] = v[key]), acc), {}) + ); + return ( + + + {propertyNames.map(val => )} + + + {filteredData.map((val, i) => ( + + {propertyNames.map(p => )} + + ))} + +
{val}
{val[p]}
+ ); +} +``` + +```jsx +const people = [ + { name: 'John', surname: 'Smith', age: 42 }, + { name: 'Adam', surname: 'Smith', gender: 'male' } +]; +const propertyNames = ['name', 'surname', 'age']; +ReactDOM.render( + , + document.getElementById('root') +); +``` + + + +