Reputation: 4447
I have a simple ReactJS application that loads a list of users and shows a record for each user.
This is the component handling the loading of the users and showing them in a list, while the UserCard
component will visualize the user information and allow for edits.
export default class UserManager extends React.Component {
constructor() {
super();
this.state = {
users:[]
};
};
componentDidMount() {
this.loadUsers();
};
loadUsers() {
$.getJSON('/api/users').then((data) => {
this.setState({ users: data.items });
});
};
render() {
return (
<div className="animated fadeIn">
<div className="row">
<div className="col-sm-8 col-md-10">
<div id="userslist" className="userlist" >
{
this.state.users.map((user) => {
<UserCard user={user} />
})
}
</div>
</div>
</div>
</div>
)
}
}
I load the users on componentDidMount, and the api call returns successfully with all user data. The rendering of the users is however not triggered. The list will remain empty.
Am I missing something here? Do I have to trigger the rendering manually again?
Upvotes: 1
Views: 701
Reputation: 281676
To add to @Mayank answer, you probably can do it without writing an explicit return statement, by using ()
instead of {}
after the map function since it automatially returns the JSX inside it by default
<div id="userslist" className="userlist" >
{
this.state.users.map((user) => (
<UserCard user={user} />
))
}
</div>
Upvotes: 1
Reputation: 104379
Return the UserCard component from map
body, if you don't return anything then, it will return undefined
by default:
<div id="userslist" className="userlist" >
{
this.state.users.map((user) => {
return <UserCard user={user} />
})
}
</div>
Or write it like this without using {}
because, you just want to return a component without any calculation or condition so {}
is not required:
<div id="userslist" className="userlist" >
{
this.state.users.map((user,i) => <UserCard key={i} user={user} /> )
}
</div>
Assign the unique key
to each UserCard
.
Upvotes: 3