Higher Order Components in React
A higher order component (HOC) in react is an advanced technique of reusing components.Basically it is a kind of common wrapper function that can take in wrapped components and convert it to a new form.
So essentially ,
A higher-order component is a function that takes a component and returns a new component.
const EnhancedComponent = higherOrderComponent(WrappedComponent);
I am showing a common example of how higher order component works:-
So,here I am making a new Button .The look of the button will be based on the style that will be passed.
We have a App.js where we are declaring the ButtonOne component
<ButtonOne disable></ButtonOne>
Now defining our ButtonOne component as:-
import React from ‘react’;import stylesWrapper from ‘../HOC/stylesWrapper’const ButtonOne = (props) => {return (<button style={props.styles}>I am ButtonOne</button>);}export default stylesWrapper(ButtonOne);
essentially what we are doing here is wrapping the buttonOne component inside the stylesWrapper.
Now defining HOC which will be function that will return component with new props and logic .
StylesWrapper.js File
import React from 'react';import commonStyles from '../styles/commonStyles';const translateProps=(props)=>{let _styles={...commonStyles.default};if(props.disable){_styles={..._styles,...commonStyles.disable}}const newProps={...props,styles:_styles}return newProps;}export default (WrappedComponent)=>{return function wrappedRender(args){return WrappedComponent(translateProps(args))}}
Here, we are defining a function called translateProps that will take all the props from the wrapped component and apply logic and return us the new props .
After that we are creating the HOC where we are creating a function that returns the component on applying translateProps() on that component .
Hope you understood the topic .
For more information you can go to the official doc :https://reactjs.org/docs/higher-order-components.html