The wrapper function takes two inputs, one is the component and the other is the class name.
My question is, why didn’t we directly use jsx codes after return?
Why did we put an arrow function after return?
If I use jsx code directly after return, I get the following error
import React from "react";
const Wrapper = (WrappedComponent, className) => {
return (props) => (
<div className={className}>
<WrappedComponent />
</div>
);
};
export default Wrapper;
2
Answers
a higher order component,
Wrapper
in your case, will be used as follows:so see how the
WrapperComponent
is being rendered? it’s being rendered as a normal react component, i.e. this syntax<WrapperComponent />
. Thus, like any other react component,WrappedComponent
can either be a class component or as in this case, a functional component (returned byWrapped
).if
Wrapped
was to return the jsx directly as you said, you wouldn’t be able to renderWrappedComponent
as react component! You would have to do the below (which is usually a counter pattern in react, and not how HOC should be used)A HOC is a function taking a component in parameter and returning a component (that eventually render the original component with extra steps). So it is not created like an usual component, it has to return a functional component.
So this
is a component, and this
is a HOC that can be used like this
You cannot call directly a HOC as a functional component because it’s not, it is a function returning a function returning JSX. So you don’t render the HOC but its returned value