How to render the same component several times in React?

Asked

Viewed 207 times

4

I’m trying to make a list with a component being repeated certain times.

To be clear, I have a ScrollView and its own component PutANumber. I need the ScrollView has a predefined amount of components PutANumber.

It would literally be something like this:

<ScrollView>
  /* Alguma expressão que coloque uma quantidade
     específica de componentes PutANumber... */
</ScrollView>

Whereas the quantity of PutANumber necessary would be 5, the code explicitly written would be:

<ScrollView>
  <PutANumber/>
  <PutANumber/>
  <PutANumber/>
  <PutANumber/>
  <PutANumber/>
</ScrollView>

How to do this?

1 answer

4

How an React component is nothing more than a mere call to React.createElement, is the same thing as creating an array with N elements.

A simple example: create an array with 5 booleans true:

const arr = Array.from({ length: 5 }).map(() => true);
console.log(arr);

Of course, in the example above you could use the Array.prototype.fill, but as we will see in the following example, Array.prototype.map is more ideal in the specific case of React, since we are obliged to pass the property key - what forces us to differ, even in the slightest, each element.

In React then it would not be very different:

function PutANumber() {
  return <div>Componente PutANumber.</div>;
}

function App() {
  return (
    <div>
      {Array.from({ length: 5 }).map((_, index) => (
        <PutANumber key={index} />
      ))}
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('#root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

The map had to be used since we need to pass a key for each component being rendered via array. A documentation explains the need for ownership key.

  • 1

    an additional problem on the site that I am realizing that the questions have positive votes and the answers have no score, this is happening in a general way in the questions and answers, at least strange. + 1 in his reply .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.