Home > Enterprise >  How to render an array of object with specified keys
How to render an array of object with specified keys

Time:10-07

I have the below array of objects I just want to display name and its image

0: {name: 'Dips & Spreads', children_count: '4', id: 3, image: 'https://wingreens-dev.codilar.in/media/catalog/category/1_1_1.png', include_in_menu: 1, …}
1: {name: 'Hummus', children_count: '0', id: 46, image: 'https://wingreens-dev.codilar.in/media/catalog/category/1_3_1.png', include_in_menu: 1, …}
2: {name: 'Greek Yogurt', children_count: '0', id: 47, image: 'https://wingreens-dev.codilar.in/media/catalog/category/2_1_1.png', include_in_menu: 1, …}

And I tried to display the name first in the below code

renderBestSellerCategories(){
    console.log('aaa', this.bestSellerCategories);
    const listItems = this.bestSellerCategories.map((d) => <li key={d.name}>{d.name}</li>);
    if(this.bestSellerCategories.length) {
       return(
            <div>
                <h1>reactjs</h1>
            </div>
       )
    }
    else{
        return(
            <div>
                {listItems}
            </div>
        )
    }
}

render(){ return( {this.renderBestSellerCategories()}) }

I am not able to display the names in the frontend. How to do that any solution please

CodePudding user response:

you can directly use bestSellerCategories

renderBestSellerCategories(){
    console.log('aaa', this.bestSellerCategories);
return (
            <div>
                {this.bestSellerCategories.map((d) => <li key={d.name}>{d.name}</li>);}
            </div>
)
    }
}

CodePudding user response:

You just need to update condition as shown on link : https://stackblitz.com/edit/demo-react-class-component-pppahy?file=Demo.js

renderBestSellerCategories(){
console.log('aaa', this.bestSellerCategories);
const listItems = this.bestSellerCategories.map((d) => <li key={d.name}>{d.name}</li>);
if(!this.bestSellerCategories.length) {
   return(
        <div>
            <h1>reactjs</h1>
        </div>
   )
}
else{
    return(
        <div>
            {listItems}
        </div>
    )
}

}

  • Related