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
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>If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With