I have three arrays persons
, skills
and personSkills
. Now I want to show all skills for each person in a unordered vertical list, like this
- Person1
- Skill1
- Skill2 - Person2
- Skill3
- Skill4
Here's my code-
let persons = ["Person1", "Person2"];
let skills = ["Skill1", "Skill2", "Skill3", "Skill4"];
export class App extends React.Component {
constructor(props) {
super(props);
this.state = {
personSkills: [
{ Person1: ["Skill1", "Skill2"] },
{ Person2: ["Skill3", "Skill4"] }
]
};
}
render() {
return (
<div className="App">
{persons.map((eachP) => (
<ul>
{eachP}
{this.state.personSkills.map((eachPS) => {
eachPS[eachP] && eachPS[eachP].map((eachS) => <li>{eachS}</li>);
})}
</ul>
))}
</div>
);
}
}
But it just shows
- Person1
- Person2
Here's a link to my sandbox - sandbox
Please help.
I have three arrays persons
, skills
and personSkills
. Now I want to show all skills for each person in a unordered vertical list, like this
- Person1
- Skill1
- Skill2 - Person2
- Skill3
- Skill4
Here's my code-
let persons = ["Person1", "Person2"];
let skills = ["Skill1", "Skill2", "Skill3", "Skill4"];
export class App extends React.Component {
constructor(props) {
super(props);
this.state = {
personSkills: [
{ Person1: ["Skill1", "Skill2"] },
{ Person2: ["Skill3", "Skill4"] }
]
};
}
render() {
return (
<div className="App">
{persons.map((eachP) => (
<ul>
{eachP}
{this.state.personSkills.map((eachPS) => {
eachPS[eachP] && eachPS[eachP].map((eachS) => <li>{eachS}</li>);
})}
</ul>
))}
</div>
);
}
}
But it just shows
- Person1
- Person2
Here's a link to my sandbox - sandbox
Please help.
Share Improve this question asked Jan 28, 2021 at 17:23 sandysandy 5391 gold badge7 silver badges24 bronze badges2 Answers
Reset to default 3You could simplify the way you store the skills as follows:
this.state = {
personSkills: {
Person1: ["Skill1", "Skill2"],
Person2: ["Skill3", "Skill4"]
}
};
Now while rendering:
render() {
return (
<div className="App">
{persons.map((eachP) => (
<ul>
{eachP}
{this.state.personSkills[eachP] && this.state.personSkills[eachP].map((skill) => {
return <li>{skill}</li>;
})}
</ul>
))}
</div>
);
}
The map
function expects a return statement.
So you need to modify your code to something like
{this.state.personSkills.map((eachPS) => {
return eachPS[eachP] && eachPS[eachP].map((eachS) => <li>{eachS}</li>);
})}