What are container components?
- Container components are primarily related to the way things work
- They rarely have any HTML except the
div
tag - Usually stateful components
- Responsible for providing data and behavior for child components (usually presentational components)
To see more clearly, let’s see the example below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Collage extends Component { constructor(props) { super(props); this.state = { images: [] }; } componentDidMount() { fetch('/api/current_user/image_list') .then(response => response.json()) .then(images => this.setState({images})); } render() { return ( <div className="image-list"> {this.state.images.map(image => { <div className="image"> <img src={book.image_url} /> </div> })} </div> ) } } |
In contrast, with presentational components?
- Presentational components are responsible for how things are displayed
- Contains very little logic handling within it
- They do not know how data is loaded or data after they render
- They are usually written as stateless functional components
For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//defining the component as a React Component class Image extends Component { render() { return <img src={this.props.image} />; } } export default Image //defining the component as a constant const Image = props => ( <img src={props.image} /> ) export default Image |
With presentational components, you have different ways to define them as ordinary react components or constants. Defining constants can eliminate dependecies and code is also more concise.
Building presentational and container components effectively makes our React application reusable and maintainable are powerful aspects of ReactJS.