Issue
Consider a simple example of the render function of a React component:
render () {
const rowLimit = this.props.rowLimit ? this.props.rowLimit : 5
return (
<tbody>
{row()}
{row()}
{row()}
{row()}
{row()}
</tbody>
)
}
Currently rowLimit
is useless.. but I would like to use that number to determine how many {rows()}
s are rendered. Is there a clean way to do this?
Using a for (let i = 0; i < rowLimit; i++)
loop feels clunky... I will award style points for a better solution
Note: row()
returns a JSX element
Solution
You can use Array#from to convert limit to an array of rows:
class Tbody extends React.Component {
render () {
const { rowLimit = 5 } = this.props; // destructure with defaults instead of trinary
return (
<tbody>
{
Array.from({ length: rowLimit }, (_, k) => (
<tr key={k}>
<td>{k}</td>
</tr>
))
}
</tbody>
)
}
}
ReactDOM.render(
<table>
<Tbody />
</table>,
demo
);
td {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="demo"></div>
Answered By - Ori Drori
Answer Checked By - - David Goodson (ReactFix Volunteer)