Search code examples
reactjsjsxarrow-functions

Higher Order Component in react js


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;



Solution

  • 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>
        );
    }