Reputation: 2117
I am trying to fill a table given variables a user provides. For example, the user will input N=10 , then an Incremental value I = 2, a max value M = 20 and it should populate a table to read from the bottom left to right like so:
16 18 20
10 12 14
How can I map the values to the cells in the table? I've been finding examples but they are mostly given sets of data in an array of objects.
https://codepen.io/anon/pen/VQQwdd
const BottomLeftValue = 10;
const IncrementalValue = 2;
const MaxValue = 30;
class TableRow extends React.Component {
render() {
const {
data
} = this.props;
const row = data.map((data) =>
<tr>
<td key={data.name}>{data.id}</td>
<td key={data.price}>{data.id+1}</td>
<td key={data.id}>{data.id+2}</td>
</tr>
);
return (
<span>{row}</span>
);
}
}
class Table extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<table>
<TableRow data={this.props.data} />
</table>
);
}
}
ReactDOM.render(<Table data={BottomLeftValue} />, document.getElementById("root"));
<div id="root"></div>
I get that it's not working because there's no data, no name, price, id etc. Trying to work off the closest example I had. Any ideas?
Upvotes: 1
Views: 1423
Reputation: 16450
If making the array and chunking it up is where you're stuck at, this might give you some idea:
const min = 10;
const step = 2;
const max = 30;
const getRange = (min, max, step, r =[]) =>
min <= max
? getRange(min + step, max, step, [...r, min])
: r;
const chunk = (n, arr) =>
arr.reduce((acc, cur) => {
var last = acc[acc.length - 1];
return last.length === n
? (acc.push([cur]), acc)
: (last.push(cur), acc[acc.length - 1] = last, acc);
}, [[]]);
const range = getRange(min, max, step);
const data = chunk(3, range);
console.log(data); // [ [10, 12, 14], [16, 18, 20], [22, 24, 26], [28, 30] ]
// rendering in react
data.map(row =>
<div className='row'>
{ row.map(col =>
<div className='column'>
{ col }
</div>)
}
</div>
);
If you have lodash
or something similar then you can just use _.range
and _.chunk
Upvotes: 1