I have the below prop being passed in my component, which should then display it.
const userData = {'name':'Tom','hobbies':['Basketball','Judo']}
const userDataDisplay = props => {
return (
<>
<h2>{props.name}</h2>
<p>{props.hobbies.map(hobby=><li>{hobby}</li>)}</p>
</>
)
}
But When I add another user, both the usernames come first and then the hobbies, when what I need is the hobbies for each user to come after the name.
Tom
Sam
Basketball
Judo
Carrom
appears instead of
Tom
Basketball
Judo
Sam
Carrom
What obvious thing am I missing?
CodePudding user response:
First of all, to have multiple users you will need an Array
, you only have one user object. If you have an array you can loop over all the users using map()
the same way you already loop over your hobbies.
Second, list items <li>
only really make sense within a list <ul>
or <ol>
. And in fact what you want is a nested list so you should use nested lists.
Here a working solution which reflects the abovementioned changes.
const userData = [
{ name: "Tom", hobbies: ["Basketball", "Judo"] },
{ name: "Sam", hobbies: ["Carrom", "Football"] },
];
const UserDataDisplay = ({ userData }) => {
return (
<ul>
{userData.map((user) => (
<li>
<ul>
<h2>{user.name}</h2>
{user.hobbies.map((hobby) => (
<li>{hobby}</li>
))}
</ul>
</li>
))}
</ul>
);
};
ReactDOM.render(
<UserDataDisplay userData={userData} />,
document.getElementById("root")
);
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="root"></div>
CodePudding user response:
that's because you need to first loop thorough your array and then base on each hobby display both h2 tag and p tag