2

How to loop for repeating

This is my code

This is App.js

import React from 'react';
import './App.css';
import Child from './Child/Child';

function App() {
  return (
    <div className="container">
      <div className='row'>
        <Child></Child>
      </div>
    </div>
  );
}

export default App;

This is Child.js

import React from 'react';
import './Child.css';

function Child() {
    return(
        <div className='container'>
            <div className='row'>
                <h1>Mark</h1>
            </div>
        </div>
    )
}

export default Child

If I am not clear with my doubt, please put a comment.

2 Answers 2

2

You could just put ten Child components into an array and render that.

const children = []
for(let i = 0; i < 10; i++){
  children.push(<Child key={i}/>)
}
  return (
    <div className="container">
      <div className='row'>
        {children}
      </div>
    </div>
  );

https://reactjs.org/docs/lists-and-keys.html#rendering-multiple-components

1

To loop n number of times, you can map over an array of length n and return your component.

function App() {
  const n = 10;
  return (
    <div className="container">
      <div className='row'>
        {[...Array(n)].map((_, index) => (
           <Child key={index} />
        ))}
      </div>
    </div>
  );
}