skip to Main Content

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

errore
Wrapper code

import React from "react";

const Wrapper = (WrappedComponent, className) => {
  return (props) => (
    <div className={className}>
      <WrappedComponent />
    </div>
  );
};
export default Wrapper;


2

Answers


  1. a higher order component, Wrapper in your case, will be used as follows:

    const WrappedComponent = Wrapper(SomeComponent, 'someClassName');
    
    const App = () => {
        // some code here you know
        
        return (
            <div>
                 ....
                 <WrapperComponent />
            </div>
        );
    }
    

    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 by Wrapped).

    if Wrapped was to return the jsx directly as you said, you wouldn’t be able to render WrappedComponent 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)

    const WrappedComponent = Wrapper(SomeComponent, 'someClassName');
    
    const App = () => {
        // some code here you know
        
        return (
            <div>
                 ....
                 {WrapperComponent}
            </div>
        );
    }
    
    Login or Signup to reply.
  2. 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

    const MyComponent = () => <div>My Component</div> 
    

    is a component, and this

    const MyHOC = (Component, className) => {
       return () => (
         <div className={className}>
            <Component />
         </div>  
       )
    }
    

    is a HOC that can be used like this

    const MyWrappedComponent = MyWrapper(MyComponent, "myClassName") // -> This returns a functional component
    
    // MyWrappedComponent can be called like a normal component (because it is)
    <MyWrappedComponent />
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search