In the world of frontend development, especially when dealing with React, two terms often cause confusion: wrapper and container. Both have different roles, and understanding these differences is crucial for effective component composition. In this article, we will look at these two elements, compare them, and provide some examples to illustrate their usage.
Wrapper | Container | |
---|---|---|
Definition | A component that encapsulates other components for styling or layout purposes. | A component connected to the application's state (Redux or any state management). It gets and sets the state and passes down props to its children. |
Usage | Layout, styling, and reusability. | Data fetching, state management. |
Child Components | Child components receive props, but mostly for UI rendering. | Child components can receive functions and state as props. |
A wrapper component in React is a component that wraps and augments other components. It's typically used for code reuse and component abstraction for styling purposes.
function WrapperComponent({ children }) {
return <div className="wrapper-style">{children}</div>;
}
In the above code, WrapperComponent is a wrapper component that wraps the children prop inside a div with a class of wrapper-style. This component can now be reused across the application to provide consistent styling.
A container component, on the other hand, is concerned with how things work. It usually defines the data that a component needs and how to get and transform that data. Container components are often generated using higher-order functions, like connect from React Redux.
import { connect } from 'react-redux';
function ContainerComponent({ data, fetchData }) {
useEffect(() => {
fetchData();
}, [fetchData]);
return <div>{data}</div>;
}
const mapStateToProps = state => ({
data: state.data,
});
const mapDispatchToProps = dispatch => ({
fetchData: () => dispatch(fetchDataAction()),
});
export default connect(mapStateToProps, mapDispatchToProps)(ContainerComponent);
Here, ContainerComponent is a container component that is connected to the Redux store. It fetches data when the component mounts and displays this data.
To conclude, while wrapper and container components might seem similar, they have different roles in a React application. A wrapper is more about presentational concerns — layout, style, and UI consistency — while a container is more about logic and state management, providing data and behavior to UI or other container components. Understanding the difference and proper usage of these components can lead to more maintainable code.