Marco Aurélio
Marco Aurélio

Reputation: 45

Loop does not work with react

My loop repetition does not work, I'm using React to render on the screen, but only one element appears and my array has 12 elements. Can someone tell me why?

import React from 'react'
import '../custom/style.css'

export default props =>{

    const renderRows = () =>{
    const list = props.list || []
     for (var i = 0; i < list.length; i++) {
        var obj = list[i];
        return (
        <div key={obj.id}>
            <p>{obj.title}</p>
            <img src={obj.images.normal} />
            </div>
        )
    } 
    
}


    return(
        <div id="demo">
        {renderRows()}
        </div>
            
    )

}

Upvotes: 0

Views: 3265

Answers (2)

andrewatkinson
andrewatkinson

Reputation: 71

Mapping over the divs is easier. The loop returns after the first iteration, thus only one <div>.

import React from 'react'
import '../custom/style.css'

export default rows = () => {
  return (
    props.list && props.list.map(obj => {
      <div key={obj.id}>
        <p>{obj.title}</p> 
        <img src={obj.images.normal}/> 
      </div>
    })
  )
}

Upvotes: 0

Mike Lowe
Mike Lowe

Reputation: 46

You're returning a <div> on the first loop iteration. You'll want to create an array and push all your elements there instead. I'd recommend using the map function i.e.

const renderRows = () => {
  const list = props.list || [];
  return list.map(obj => (
    <div key={obj.id}>
      <p>{obj.title}</p>
      <img src={obj.images.normal} />
    </div>
  ));
};

Upvotes: 2

Related Questions