Reputation: 83
I have a component defined as shown below. creativeList
contains values that I'm interested in displaying. It contains the following:
creativeList = [{keyID: "AC072", cost: 1461, people: 520, cpp: "2.81"},
{keyID: "AC098", cost: 1600, people: 470, cpp: "3.4"}]
I would like to be able to display the keyID
by returning it in my component. I am able to get the value by logging to the console, however, I'm not able to return it. Can someone help me out?
function DisplayList(props) {
const creativeList = props.creativeList
function ret(){
creativeList.forEach(function(item){
const i = item[0]
console.log(i.keyID)
return (
<li>{i.keyID}</li>
);
})
}
return (
<div>
<li>List:</li>
{ret()}
</div>
);
}
export default DisplayList;
Upvotes: 0
Views: 99
Reputation: 11001
You can simplify using the map
. Also add the key
attribute to each element in list.
function DisplayList(props) {
const { creativeList = [] } = props.creativeList;
return (
<div>
<div>List:</div>
{creativeList.map(({ keyID }) => (
<li key={keyID}>{keyID}</li>
))}
</div>
);
}
export default DisplayList;
Upvotes: 1
Reputation: 10025
Add a return statement just before forEach statement and replace forEach by map
map returns an array of the elements returned by its callback parameter, unlike forEach.
forEach returns undefined, that's why your list is not getting print.
function ret(){
return creativeList.map(function(item){
console.log(item.keyID)
return (
<li>{item.keyID}</li>
);
})
}
Upvotes: 3
Reputation:
There is no way to stop forEach, if you want to do return, forEach returns undefined, use map instead. working example: sandbox
Upvotes: 1
Reputation: 557
Try This. You missed to return a component and ofcourse you should use map instead of foreach
import React from "react";
function DisplayList(props) {
const creativeList = props.creativeList;
function ret() {
return creativeList.map(function(item) {
const i = item;
console.log(i.keyID);
return <li>{i.keyID}</li>;
});
}
return (
<div>
<li>List:</li>
{ret()}
</div>
);
}
export default DisplayList;
Upvotes: 2