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(
{
this.state.posts.map(post => {
return
})
}
);
}
}
Example of a presentational component written as a class component
import React, { Component } from 'react';
class PostTitle extends Component{
render(){
return Post title: {this.props.postTitle}
;
}
}
export default PostTitle;
Example of a presentational component written as a function component
import React from 'react';
function PostTitle(props) {
return Post title: {props.postTitle}
;
}
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 Post title: {props.postTitle}
;
}
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