Reputation: 2290
Pretty sure that I am missing something simple but this code has me banging my head.
I have an array
in a local json
file as
{
"type": [
{
"name": "Accommodation",
"icon": "🏨",
"subcategory": [
"Hotels",
"Motels",
"Bed & Breakfasts"
]
},
{
"name": "Guided Tours",
"icon": "🚌",
"subcategory": [
"Audio & Self Guided",
"Cruises, Sailing & Water",
"Food, Wine & Nightlife"
]
}
]
}
and importing into a React component as
import { type } from './assets/json/company-type.json';
then I am using filter
to the name
of companyType
(which is based on a select
value of either Accommodation
or Guided Tours
. After I map the returned items before map
the subcategory
<ul>
{type
.filter(item => {
return item.name === companyType;
})
.map(item => {
item.subcategory.map(subcategory => {
<li key={subcategory}>
<label id={subcategory} htmlFor={subcategory}>
<input
type="radio"
name={subcategory}
value={subcategory}
/>
<span />
{subcategory}
</label>
</li>;
});
})}
</ul>
However, nothing is returned. Yet if I log
subcategory
I get each returned in the console. What am I missing?
Upvotes: 0
Views: 49
Reputation: 61
This is because you are not returning from .map() methods. Use this modified code and it will work as expected
<ul>
{type
.filter(item => {
return item.name === "Accommodation";
})
.map(item => {
return item.subcategory.map(subcategory => {
return (
<li key={subcategory}>
<label id={subcategory} htmlFor={subcategory}>
<input
type="radio"
name={subcategory}
value={subcategory}
/>
<span />
{subcategory}
</label>
</li>
);
});
})}
</ul>
codeSandbox link: https://codesandbox.io/s/4881483j7x
Upvotes: 1