Strahinja Ajvaz
Strahinja Ajvaz

Reputation: 2633

How to use a HOC with a class Component

I've spend the last couple of hours looking at how to render this but i can't get my head around it.

const Test = props => (
  <p>
    {console.log(props)}
    {props.children}
  </p>
)

const changeColor = WrappedComponent => props => {
  return class extends React.Component {
    render() {
      return (
        <WrappedComponent style={{ color: props.color }} test="adasd">
          {props.children}
        </WrappedComponent>
      )
    }
  }
}

const Temp = changeColor(Test)

When i go to render it it tells me that Functions are not valid as a React child. How would i return a Class Component as i need to have access to state.

Upvotes: 3

Views: 5168

Answers (1)

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

That's because changeColor is

function that return function that returns class component

To make your code work you would need to:

const props = {};

const Temp = changeColor(Test)(props)

However, I think you don't need that function with props as an argument:

const changeColor = WrappedComponent => {
  return class extends React.Component {
    render() {
      return (
        <WrappedComponent style={{ color: this.props.color }} test="adasd">
          {this.props.children}
        </WrappedComponent>
      )
    }
  }
}

const Temp = changeColor(Test)

Upvotes: 4

Related Questions