I'm trying to iterate and display certain values of a JSON on my web application using ReactJS.
My render looks like this:
render() {
const orders =
Object.keys(this.state.data).map((e,i) => {
return (
<div key = {i}>
<div>ID: {this.state.data[e].id}</div>
<div>Email: {this.state.data[e].email}</div>
<div>Note: {this.state.data[e].note}</div>
<div>{this.findValue(e)}</div>
</div>
)
})
return (
<div>
<div>
{orders}
</div>
</div>
);
}
Now everything looks fine until I run this.findValue where it immediately returns after the first iteration instead of returning multiple divs.
findValue = (e) => {
for(let key2 in this.state.data[e].line_items) {
return (
<div>
Line item: {this.state.data[e].line_items[key2].title}
</div>
)
}
How would I be able to return every line item? Thanks in advance.
When you return something from the function given to map, you are just returning what the current element should be mapped to in the new array. When you return inside the for..in, you are returning from the findValue method instead.
You could use map on the array of keys in line_items as well.
findValue = e => {
const { line_items } = this.state.data[e];
return Object.keys(line_items).map(key => (
<div key={key}>Line item: {line_items[key].title}</div>
));
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With