How to run a loop to place components in react native

Viewed 41

I have a picker that allows user to select a number from 1 to 5 and based on the selection lets say user picks 2 a next screen shows that should run a loop 2 times and display the component two times. I have this code as of now:

function IndividualInfoCard({ noOfInd }) {

    var noOfIndSelected = noOfInd;

    return (
        <View>
            <IndividualInfo title={'Person 1'} />
            <IndividualInfo title={'Person 2'} />
            <IndividualInfo title={'Person 3'} />
            <IndividualInfo title={'Person 4'} />
            <IndividualInfo title={'Person 5'} />
        </View>
    );
}

These 5 components I need to place all of these as per the number in noOfIndSelected. I searched but couldn't figure out how to do it with .map so how do I achieve it?

1 Answers

Have you tried doing a simple for?

I leave you a simple example.

 export default function App() {
   let items = [];
   for (var i = 0; i < 9; i++) {
    items.push(<li key={i}>hOLA</li>);
   }
   return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {items}
    </div>
   );
  }

Applied in your code it would be like this:

function IndividualInfoCard({ noOfInd }) {

 var noOfIndSelected = noOfInd;
 var items = []
 for (var i = 0; i < noOfIndSelected; i++) {
   items.push(<IndividualInfo key={i} title={'Person '+i} />);
 }
 return (
    <View>
        {items}
    </View>
 );
}

CodeSandbox

Sorry, it's my first answer on stackoverflow

Related