How to define a Higher Order Component (HOC) in React

const getRGBColor = () => parseInt(Math.random() * 255, 10)
const randomColor = () => [,,,].fill().map(getRGBColor).join(',')

export default randomColor
import React, { Component } from 'react'

import randomColor from './randomColor'

const withColor = (Tag) => {
  class WithColor extends Component {
    changeColor () {
      const color = randomColor()
      const backgroundColor = randomColor()
      this.style = { color, backgroundColor }
    }
    render = () => {
      const { changeColor } = this
      const props = {...this.props, changeColor }
      return <Tag {...props} />
    }
  }
  const { displayName, name } = Tag  
  const tagName = (displayName || name || 'Component')
  WithColor.displayName = `WithColor(${tagName})`
  return WithColor
}

export default withColor

Last updated

Was this helpful?