Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically render JSX component X times?

Tags:

reactjs

jsx

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

like image 540
Cumulo Nimbus Avatar asked Oct 27 '25 14:10

Cumulo Nimbus


1 Answers

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>
like image 147
Ori Drori Avatar answered Oct 29 '25 04:10

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!