Users component

The Users component in client/user/Users.js, shows the names of all the users fetched from the database, and links each name to the user profile. This component can be viewed by any visitor to the application and will render at the path '/users':

In the component definition, we first initialize the state with an empty array of users.

mern-skeleton/client/user/Users.js:

class Users extends Component {
state = { users: [] }
...

Next, in componentDidMount, we use the list method from the api-user.js helper methods, to fetch the user list from the backend, and load the user data into the component by updating the state.

mern-skeleton/client/user/Users.js:

  componentDidMount = () => {
list().then((data) => {
if (data.error)
console.log(data.error)
else
this.setState({users: data})
})
}

The render function contains the actual view content of the Users component, and is composed with Material-UI components such as Paper, List, and ListItems. The elements are styled with the CSS defined and passed in as props.

mern-skeleton/client/user/Users.js:

render() {
const {classes} = this.props
return (
<Paper className={classes.root} elevation={4}>
<Typography type="title" className={classes.title}>
All Users
</Typography>
<List dense>
{this.state.users.map(function(item, i) {
return <Link to={"/user/" + item._id} key={i}>
<ListItem button="button">
<ListItemAvatar>
<Avatar>
<Person/>
</Avatar>
</ListItemAvatar>
<ListItemText primary={item.name}/>
<ListItemSecondaryAction>
<IconButton>
<ArrowForward/>
</IconButton>
</ListItemSecondaryAction>
</ListItem>
</Link>
})}
</List>
</Paper>
)
}

To generate each list item, we iterate through the array of users in the state using the map function.

To add this Users component to the React application, we need to update the MainRouter component with a Route that renders this component at the '/users' path. Add the Route inside the Switch component after the Home route.

mern-skeleton/client/MainRouter.js:

<Route path="/users" component={Users}/>

To see this view rendered in the browser, you can temporarily add a Link component in the Home component to route to the Users component:

<Link to="/users">Users</Link>