Sometimes we need to share props and behaviour between multiple components/containers. For that we can do a higher order component. Example:
Higher Order Component that will decorate other component:
import { Component } from "React";
import { connect } from "react-redux";
function Decorate(ComponentToDecorate) {
class ComponentDecorated extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
// fetch data and stuff
}
render() {
return <ComponentToDecorate {...this.props} />;
}
}
function mapStateToProps(state) {
return {
// your shared props
};
}
const mapDispatchToProps = {
// your shared action call
};
return connect(mapStateToProps, mapDispatchToProps)(ComponentDecorated);
}
export default Decorate;
The actual component that will inherite stuff from the Higher Order Component
import React, { Component } from "react";
import { connect } from "react-redux";
import Decorate from "Decorate.react";
class SomeComponent extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
}
componentWillReceiveProps(nextProps) {
}
render() {
<p> Hello </p>
);
}
function mapStateToProps(state) {
return {
// component specific props
};
}
const mapDispatchToProps = {
// component specific action call
};
export default connect(mapStateToProps, mapDispatchToProps)(Decorate(SomeComponent));
Redux provides a
compose
utility function to make the syntax a little easier on the eyes. It takes functions as arguments, and returns a function that applies those functions right to left. That way, your line:would become