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 randomColorimport 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 withColorPreviousHow can I use context to selectively pass data down a component hierarchy? (2 approaches)NextWhat are the different lifecycle methods in React?
Last updated
Was this helpful?