cbll
cbll

Reputation: 7219

Why won't for ... in loop here?

I have a variable containing N objects. For each object, I wish to pass these to a child component - so we will have N amount of child components with different props as well.

Parent:

    renderBrandCards() {

        const { marketData } = this.state;

        let i = 0;
        for (const stock in marketData){
            i++;
            return (
                <BrandCard
                    key={i}
                    stock_name={stock}
                    stock_data={marketData[stock]}
                />
            )
        }
   }
   // .... render etc
    return (
        <ScrollView>
            {this.renderBrandCards()}
        </ScrollView>
    )

However, only the first object of marketDataMap gets passed to BrandCard component and rendered. It doesn't loop.

Am I using for ... in wrong here?

Upvotes: 1

Views: 60

Answers (1)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48407

Am I using for ... in wrong here?

Yes, because you're are returning from function after first step of for loop.

You have to create an array which will contains all the desired items and then just return the array.

let i = 0;
let brandCards = [];
for (const stock in marketData){
        i++;
        brandCards.push(
            <BrandCard
                key={i}
                stock_name={stock}
                stock_data={marketData[stock]}
            />
        )
}
return brandCards;

But I recommend you to use another approach with map method.

return Object.keys(marketData).map(function(key, i){
     return (<BrandCard key={i} stock_name={key} stock_data={marketData[key]}/>);
});

Upvotes: 1

Related Questions