/

React: Presentational vs Container Components

React: Presentational vs Container Components

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:

1
2
3
4
5
6
7
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.