Reputation: 11
I have a state that has an array of objects each object has a name property, I created a function to loop over the array and display the name property of each object when I call the function there is nothing on the screen why is that I am 100% sure the function is working I console.log
the objects and name Property it's there
import React, { Component } from 'react';
class Products extends Component {
constructor(props) {
super(props);
this.showItems = this.showItems.bind(this);
this.state = {
products: [
{
id: 1,
name: 'Espresso',
price: 5.5,
summary: 'Galão, grinder mocha',
show: true,
showText: false,
},
{
id: 2,
name: 'Americano',
price: 10.5,
summary: 'Galão, grinder mocha',
show: true,
showText: false,
},
{
id: 3,
name: 'Latte',
price: 7.5,
summary: 'Galão, grinder mocha',
show: true,
showText: false,
},
{
id: 4,
name: 'Flat white ',
price: 3.5,
summary: 'Galão, grinder mocha',
show: true,
showText: false,
},
{
id: 5,
name: 'Mocha',
price: 15,
summary: 'Galão, grinder mocha',
show: true,
showText: false,
},
],
};
}
showItems() {
this.state.products.map((el) => {
return <div>{el.name}</div>;
});
}
render() {
return (
<div className="products">
<h1>Products</h1>
<div className="items">{this.showItems()}</div>
</div>
);
}
}
export default Products;
here is a screenshot of the console.log
Upvotes: 0
Views: 91
Reputation: 11
I forgot the return statement in my showItems()
function
return this.state.products.map((el) => {
return <div>{el.name}</div>;
});`
Upvotes: 0
Reputation: 5852
You can write JS code
into your html as JSX
. Hence you use map function to iterate and generate your element as below:
render() {
return (
<div className="products">
<h1>Products</h1>
<div className="items">
{this.state.products.map((el) => {
return <div>{el.name}</div>;
})}
</div>
</div>
);
}
Upvotes: 1