Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access props in a functional HOC?

I have code similar to the following:

const HOC = (props, WrappedComponent) => {
    return (
       <>
          <WrappedComponent />
          <Icon className="props.iconStyles" />
       </>
     );
};

This is not actually valid code, but you can hopefully see what I'm trying to accomplish. I want to be able to use it in the following way:

<HOC iconStyles="icon-stuff">
    <TheComponentIWantToWrap>
</HOC>

How can I write this correctly, so as to be able to pass props through? I think I might need to be using children here too, not sure.

like image 223
temporary_user_name Avatar asked Oct 07 '19 19:10

temporary_user_name


People also ask

Can functional components have props?

Functional components can accept and use props. Functional components should be favored if you do not need to make use of React state.


1 Answers

It would be something like this.

const HOC = (WrappedComponent) => {

  const MyComponent = props => {
    return (
       <>
          <WrappedComponent {...props} />
          <Icon className={props.iconStyles} />
       </>
     );
   }
   
  return MyComponent;
};
like image 65
he77kat_ Avatar answered Oct 12 '22 20:10

he77kat_