قالب وردپرس درنا توس
Home / Tips and Tricks / What are presentation and container components in React? – CloudSavvy IT

What are presentation and container components in React? – CloudSavvy IT



Reply logo on a dark background

React has a component-based architecture that encourages you to split your codebase into reusable units of functionality. However, not all components are created equal. Let’s take a look at the differences between two common types, presentation and container components (also known as “Stateful”).

Is there a state?

To begin with, it should be emphasized that these terms do not refer to any specific React function. They describe a writing style of React components that helps to maintain modularity and separate concerns. The existence of the two component types stems from choices made in your codebase.

There is only one distinguishing factor: container components have status components and presentation components do not. In practice, this means that a container part always relies on Reacts setState() method. A presentation component will never use the state.

View examples

Here̵

7;s a simple presentation component:

import React from "react";
 
class Presentational extends React.Component {
 
    render() {
        return <h1>{this.props.title}h1>;
    }
 
}
 
export default Presentational;

The component is extremely simple. It yields a single h1 tag that displays text coming through title support. Now let’s take a look at a stateful container component:

import React from "react";
 
class Container extends React.Component {
 
    constructor(props) {
        super(props);
 
        this.state = {
 
            time: (new Date()).toString()
 
        };
 
    }
 
 
    componentDidMount() {
        setInterval(() => {
            this.setState({time: (new Date()).toString()});
        }, 1000);
    }
 
 
    render() {
        return <h1>{this.state.time}h1>;
    }
 
}
 
export default Container;

The container component render method is almost identical to that in the presentation component. The difference is that the container component gets its text from within, instead of relying on an external value passed as a prop.

Every second the container component calls setState() to time key in its state. This causes React to render the component again and display the new time. Our container has its own state.

Features of each type

Several unique characteristics often occur in both presentation and container components. Looking at the presentation components first, it is likely that most of their code is within the render method. They will contain very little logic as their behavior is determined by the outside world.

Presentation components are completely unaware of where their data comes from. They don’t know when (and if) it will change. Some examples may not even accept props. Here’s a decorative element that simply displays a specific image file:

export () =>

Container components are pretty much the opposite of their presentation counterparts. You will usually find that most of your site’s logic ends up in a container component. The render method can be relatively short as you will spend a lot more lines fetching data from external sources, transforming it to your needs and then storing it in the state.

A container component render method can consist of a single line representing a presentation component. You now have a strong separation of concerns, where both components have different roles that the other fully respects. The container component collects the data; the presentation component puts it on the screen.

This is what it looks like in practice:

import React from "react";
 
const View = ({title, body}) => (
    <div>
        <h1>{title}h1>
        <p>{body}p>
    div>
);
 
class BlogPostComponent extends React.Component {
 
    constructor(props) {
        super(props);
 
        this.state = {
 
            blog: null
 
        };
 
    }
 
 
    componentDidMount() {
        fetch("/blog-post.json")
            .then(response => response.json());
            .then(blog => this.setState({blog}));
    }
 
 
    render() {
        return (
            <View
                title={this.state.blog.headline}
                body={this.state.blog.content} />
        );
    }
 
}}

BlogPostComponent is our container component. It loads a message over the network. The data is then sent to the View component for display. View It doesn’t matter where it gets its data – in the future we could reuse it to display messages fetched from a third party API, such as Facebook or Twitter.

Container components are so named because they tend to encapsulate entire functional areas of your app. They make your project work and represent the app’s back-end systems.

In a real codebase, BlogPostComponent would have even more responsibility. It should keep track of whether the message has loaded and handle errors while getting it from the network. Consequently it is render method may include some basic logic to change what is displayed – an error message, a progress bar, or our presentation View component. Presentation components never have a greater responsibility than displaying a specific portion of the user interface in the DOM.

Advantages of separating presentation and container components

Using this pattern will help you organize your code base and prevent components from becoming too unwieldy. While not a hard and fast rule, careful separation of the two types improves maintainability as the number of components in your project increases.

Try to look for opportunities to refactor as a container component render method is growing. You can probably split much of its content into a new presentation component. This makes it easier to reuse the presentation code in the future. It becomes self-contained and can operate independently of a specific data source.

Stateful components are less likely to be reused. Non-trivial behaviors naturally accumulate in them, resulting in dependence on the outside world. That’s not to say they can not will be reused, however – a two-stage confirmation button will contain the internal status (to determine whether to display “Reset User’s Password” or “Are You Sure?”), but will also be implemented throughout your codebase.

If you deliberately differentiate between Presentional and Container components, you may know better where the state of your application is. Minimizing the number of status components contributes to a maintainable codebase and helps separate concerns.

If you can’t decide whether a component should keep state, keep coding and refactor later – it’s probably too early in your project lifecycle to know where the complexity (and thus state) converges.


Source link