When working with React components, it is common to divide them into two categories: presentational components and container components.
Presentational components are primarily responsible for generating the markup to be rendered. They do not manage any state, except for state related to the presentation itself.
On the other hand, container components are mainly concerned with the “backend” operations. They handle the state of various sub-components, wrap multiple presentational components, and may interact with libraries such as Redux.
To simplify the distinction, presentational components focus on the appearance, while container components focus on making things function.
For example, consider the following presentational component. It receives data from its props and focuses only on displaying an element:
const Users = (props) => (
<ul>
{props.users.map((user) => (
<li>{user}</li>
))}
</ul>
);
In contrast, the following is a container component. It manages and stores its own data, and utilizes the presentational component to render it:
class UsersContainer extends React.Component {
constructor() {
this.state = {
users: [],
};
}
componentDidMount() {
axios.get('/users').then((users) => this.setState({ users: users }));
}
render() {
return <Users users={this.state.users} />;
}
}
Tags: React, Presentational Components, Container Components, State Management.