'How to map React component under correct category
I am able to map 3 objects as a normal list however how can I map it under the correct heading?
One way is to push each object to it's own array e.g. const employed = [] but it looks messy. Any suggestions for a better approach?
export const App = () => {
const [list, setList] = useState([
{ name: "foo", status: "student" },
{ name: "bar", status: "employed" },
{ name: "foo", status: "unemployed" },
])
const items = list.map(({name, status}, index) => {
<Profile ... />
})
return (
<div>
<div>
<h1>Students</h1>
</div>
<div>
<h1>Employed</h1>
</div>
<div>
<h1>Unemployed</h1>
</div>
</div>
)
}
Solution 1:[1]
Making three seperate lists using filter() would be one way to do it. Then you can show them as you need:
export const App = () => {
const [list, setList] = useState([
{ name: "foo", status: "student" },
{ name: "bar", status: "employed" },
{ name: "foo", status: "unemployed" },
])
const students = list.filter(x => x.status === 'student' ).map(x => <Profile... />);
const employed = list.filter(x => x.status === 'employed' ).map(x => <Profile... />);
const unemployed = list.filter(x => x.status === 'unemployed' ).map(x => <Profile... />);
return (
<div>
<div>
<h1>Students</h1>
{students}
</div>
<div>
<h1>Employed</h1>
{employed}
</div>
<div>
<h1>Unemployed</h1>
{unemployed}
</div>
</div>
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tushar Shahi |
