Use of HOC in React

Pattern in react to share common functionality between components without repeating the code.

HOC, takes a component as a argument, transforms a component into another component, adds additonal data or functionality and returns a component.


  
const HocComponent = (BaseComponent) => { 
 //create a new component from old and update new functionality
 class NewCompoent extends React.Component{
  render(){
    
return  
} } return NewComponent; } //use like this, const NewCompoent = HocComponent(BaseComponent); Example: Lets create a theme context, //themeContext.js import React from 'react'; export const themes = { light: { foreground: '#000000', background: '#eeeeee', }, dark: { foreground: '#ffffff', background: '#222222', }, }; export const themeContext = React.createContext(themes.dark); //default theme Lets create withTheme HOC, //withTheme.js import React from 'react'; import { themeContext } from '../context/themeContext'; const withTheme = (BaseComponent) => { class NewComponent extends React.Component{ render(){ return (
 
); } } NewComponent.contextType = themeContext; return NewComponent; }; export default withTheme; Let's use the theme using withTheme hoc, lets create a sample component displays a banner message, //bannerMessage.js import React from 'react'; import withTheme from '../hoc/withTheme'; const BannerMessage = (props) => { return (
This is banner message
); }; export default withTheme(BannerMessage); Now, use the banner massege in app.js without any change import BannerMessage from './components/BannerMessage'; inside render(){ return (
 
) }

Comments