Reputation: 584
Hey guys i have and object that contains key as the states and its value as array of cities for which i wanna loop over in render method and show the data
For example my object is like
{
A:{cities:[0,1,2,3]},
B:{cities:[0,1,2,3]}
}
so in render method i called
render(){
{this.renderAllStates()}
}
and then
renderAllStates = () => {
console.log(data);
// let parsedData=JSON.parse(states)
for (let [key, value] of Object.entries(data)) {
console.log(key, value.cities);
return <Collapsible trigger={key}>
<p>
This is the collapsible content. It can be any element or React
component you like.
</p>
<p>
It can even be another Collapsible component. Check out the next
section!
</p>
</Collapsible>;
}
};
so this renders only the first state inside my component, cause i am using
return
but then if i do not use return it says
Expected an assignment or function call and instead saw an expression no-unused-expressions
so my question is where should i use the return method keyword here ?
Upvotes: 0
Views: 45
Reputation: 841
To get all the elements, you need to store them in an array and return. Better use .map function in the following way.
renderAllStates = () => (
Object.keys(data).map((key) => (
<Collapsible trigger={key}>
<p>
This is the collapsible content. It can be any element or React
component you like.
</p>
<p>
It can even be another Collapsible component. Check out the next
section!
</p>
</Collapsible>
))
)
For value, use data[key].
I hope it works for you.
Upvotes: 1
Reputation: 1074385
If you want to render multiple items, you have to return an array or a React fragment. In this case, an array makes sense:
renderAllStates = () => {
return Object.entries(data).map(([key, value]) =>
<Collapsible key={key} trigger={key}>
<p>
This is the collapsible content. It can be any element or React
component you like.
</p>
<p>
It can even be another Collapsible component. Check out the next
section!
</p>
</Collapsible>
);
};
Note I added a key
property, since these are entries in an array. React needs the key to track things when the array changes.
Upvotes: 3