Posted

2 minutes read

Presentational components

Definition

Presentational components are usually stateless components / components that do not manage state and are used for displaying data.
Presentational components are usually children of container components.

Characteristics of presentational components

  • presentational components are stateless
  • they receive the date to be displayed from the parent components

Container components

Definition

Container components are usually stateful components/components that manage state, components that have the responsibility of how things work.
Container components are usually parents of presentational components.

Characteristics of container components

  • usually do not have any HTML tags besides sometimes
  • usually stateful components
  • they provide data to the children components (to the presentational components)

Example of a container component


import React, { Component } from 'react';
import PostTitle from './PostTitle';

class PostList extends Component{

	constructor(props){
		super(props);
		
		this.state = {
			posts: []
		};
	}		
	
	
	componentDidMount(){	
		fetch('https://jsonplaceholder.typicode.com/posts')
			.then(response => response.json())
			.then(json => this.setState({posts:json}));
	}

	render(){
		
		return( 

			<div>
				{
					this.state.posts.map(post => {
						return <PostTitle postTitle={post.title}/>
					})
				}
			</div>
		);
	}
}

Example of a presentational component written as a class component


import React, { Component } from 'react';

class PostTitle extends Component{
	render(){
		return <h1>Post title: {this.props.postTitle}</h1>;	
	}
}

export default PostTitle;

Example of a presentational component written as a function component


import React from 'react';

function PostTitle(props) {
		return <h1>Post title: {props.postTitle}</h1>;		
}

export default PostTitle;

Example of a presentational component written as a function component using the arrow function


import React from 'react';

const PostTitle = (props) => {
		return <h1>Post title: {props.postTitle}</h1>;		
}

export default PostTitle;

In the end we have broken up our application into two components:

  • PostTitle which does not manage any state / stateless and is a presentational component
  • PostList which manages the state (stateful) and is a container component




Thanks for reading. I hope you learned something interesting about React!
If you found this article useful, please share it with others. Don’t forget to subscribe to get notified for the upcoming articles.