Home > other >  How do I return components in React x amount of times?
How do I return components in React x amount of times?

Time:08-14

I want to return <Component/> multiple times, in this for loop: var i = 0;i < products.length;i

It should return <Component /> five times because products.length = 5.

When I try returning this in my for loop it only returns one Component.

My code is here.

The array, products, is defined here.

Thanks

CodePudding user response:

You should add the 5 Product elements to a list rather than just returning one element in the for loop. If you use the return keyword inside the for loop, it will break the loop and stop executing afterwards.

E.g.

let result = []

For(let i = 0; i < products.length; i  ) {
  result.push((
    <div className="col-md-3">
      <div className="card">
        <Link to={products[i].link}><img className="card-img-top" src={products[i].image} alt="Card cap" /></Link>
        <div className="card-body">
         <h5 className="card-title"> 
           {products[i].name}
         </h5>
         <p className="card-text"> 
          {products[i].description}
         </p>
       </div>
     </div>
   </div >
     ));
}

return result

You can then use the resulting array inside your render function in combination with the map function to display all the elements.

(I would rather put all the products in a normal JS array and just map over that inside your render function.)

If you want some additional reading, check out https://reactjs.org/docs/lists-and-keys.html

CodePudding user response:

The reason your code does not work is on the first loop, it returns the entire component. It will never reach the second loop. You probably want to use map for your use case. Since map accepts a callback thats called for each item in the array, and you return the representation of the product for each entry from that callback (rather than returning in the actual component), you wont have the issue anymore.

const YourComponent = () => {
    return products.map((product) => (
                   <div className="col-md-3">
                        <div className="card">
                            <Link to={product.link}><img className="card-img-top" src={product.image} alt="Card cap" /></Link>
                            <div className="card-body">
                                <h5 className="card-title">{product.name}</h5>
                                <p className="card-text">{product.description}</p>
                            </div>
                        </div>
                    </div>
    ))

}
  • Related