Reputation: 523
I can't seem to pass certain items into an item
prop if they relate to the category that I am looping through
I have a JSON
like this:
{
"Categories": [
{
"Name": "Music",
},
{
"Name": "Comedy",
},
{
"Name": "Sport",
},
{
"Name": "Family",
},
],
"Items": [
{
"Name": "Dolly Parton",
"NameId": "dolly-parton",
"Category": "Music",
},
{
"Name": "Cee Lo Green",
"NameId": "cee-lo-green",
"Category": "Music",
},
{
"Name": "Take That",
"NameId": "take-that",
"Category": "Music",
},
{
"Name": "Football",
"NameId": "football",
"Category": "Sport",
},
{
"Name": "Hockey",
"NameId": "hockey",
"Category": "Sport",
}
]
}
I'm looping through all the categories and then printing them into a list while trying to only pass items that relate to that category in an items
prop. I have the code below but it is passing all my data to each element and I'm not sure why.
class CategoryItems extends Component {
constructor(props) {
super(props);
}
state = {
items: this.props.items,
categories: this.props.categories,
};
render() {
const items = this.state.items;
return (
<section className="category-wrapper">
<div className="container">
<div className="category-wrapper__inner">
{this.state.categories.map((category, index) => (
<CategoryItem
key={category.Name}
items={items.map((item, index) => {
item.Category === category.Name ? item : '';
})}
/>
))}
</div>
</div>
</section>
);
}
}
All the data is there and in the react dev-tools it says each element has 667 items but I know there should only be 7 items on the sports category.
Upvotes: 0
Views: 152
Reputation: 1262
You can try this ,
class CategoryItems extends Component {
constructor(props) {
super(props);
}
state = {
items: this.props.items,
categories: this.props.categories,
};
render() {
const items = this.state.items;
const renderList = this.state.categories.reduce((total, category) => {
const list = items.filter(item => item.Category === category.Name);
if(list.length > 0){
total.push(<CategoryItem
key={category.Name}
items={list}
/>);
}
return total
},[])
return (
<section className="category-wrapper">
<div className="container">
<div className="category-wrapper__inner">
{renderList}
</div>
</div>
</section>
);
}
}
Upvotes: 0
Reputation: 2548
Apply a filter instead of a map.
<CategoryItem
key={category.Name}
items={items.filter(i => item.Category === category.Name)}
/>
Upvotes: 1