0

I am unable to use the react feature of HOC with functional component. In below code export default HOC({component: SampleComponent}) doesnt work

const SampleComponent: FC = () => {
  return (<div>Hello World</div>);
};

export default HOC({ component: SampleComponent });

And the HOC is simply

const HOC = ({ component: Component }) => {
  return (<Component/>);
}
brietsparks
  • 4,776
  • 8
  • 35
  • 69
Prerna shah
  • 321
  • 3
  • 20

1 Answers1

0

HOC should be

const HOC = ({ component: Component }) => {
  return (props: {}) => (<Component/>);
}
brietsparks
  • 4,776
  • 8
  • 35
  • 69
  • Great ! Thanks this worked. Can you also tell why do we need to return a callback function and not the component directly? – Prerna shah Apr 12 '20 at 06:52
  • @Prernashah A HOC is a function that returns a component. The callback is a component that takes no props. – brietsparks Apr 12 '20 at 07:18
  • How can i use hooks in HOC now? – Prerna shah Apr 12 '20 at 08:08
  • Can HOC not be considered as a functional component? It certainly returns React element ie Component here. – Prerna shah Apr 12 '20 at 08:32
  • Also want to render this component conditionally , something like this-
    {!id ( ) : ( )}
    Here id is coming as a response from graphql query hook, which again i am unable to use in HOC function.
    – Prerna shah Apr 12 '20 at 08:57
  • A component is not an element. A component returns an element. And a HOC returns a component. An HOC is technically not a component because it does not return an element. – brietsparks Apr 12 '20 at 09:03
  • So can we not use hooks in HOC function? – Prerna shah Apr 12 '20 at 09:12
  • Or can we not make HOC return a react element wrapping our component?Something like this-
    – Prerna shah Apr 12 '20 at 09:24
  • I would suggest: mark the above answer as correct, and then post a new question with all the things you would like to know. It is easier for you to format your code examples that way, and other people can answer as well. – brietsparks Apr 12 '20 at 19:12