Simplifying Component Logic in React with Higher-Order Components

/// Definition of Higher Order Componentimport React from 'react' 
const higherOrderComponent = WrappedComponent => {
class HOC extends React.Component
{
render() {
return <WrappedComponent />
}
}
return HOC;
}
/// Usage of Higher Order Component

// React component
const HOC = higherOrderComponent (WrappedComponent);
// You can use HOC component wherever needed
< HOC />
/// Definition of Higher Order Component with modification of prop age
import React from 'react';
const Enhancer = (WrappedComponent) => {
class HOC extends React.Component {
render() {
return (<WrappedComponent {...this.props} age={42}/> );
}
}
return HOC;
};
export default Enhancer;/// Using Higher Order Component with Enhancerimport React from 'react';,
import Enhancer from 'components/withUserAge’;
class DisplayTheAge {
render() {
return <div>User’s age is {this.data}</div>;
}
}
export default Enhancer(DisplayTheAge);
  • Render Hijacking
  • State & Props Manipulation

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store