Search code examples
javascriptreactjsarrow-functionshigher-order-components

What are two arrows in a function in higher order function in React Javascript


Following is an example HOC function I am looking at but didn't get its meaning in terms of two arrows specially the second one where we are de structuring children and props.

const HOCFunction = (PassComponent) => ({children, ...props}) => {
  return (<PassComponent {...props}>
    {children.split("").reverse().join("")}
  </PassComponent>)
}

From the definition mentioned on React docs:

Higher-order component is a function that takes a component and returns a new component.

So what exactly this second params is for?

Whole code:

const reverse = (PassedComponent) =>
  ({ children, ...props }) =>
    <PassedComponent {...props}>
      {children.split("").reverse().join("")}
    </PassedComponent>

const name = (props) => <span>{props.children}</span>
const reversedName = reverse(name)
<reversedName>Hello</reversedName>

Solution

  • HOCs, defined like this, are really just higher order functions. Functions that return functions. In this case the first function accepts a react component to decorate, and returns a functional component whose parameters are the props of the component that will ultimately be used.

    Perhaps it is better illustrated broken down a bit.

    // decorate some passed component
    const reverse = (PassedComponent) => {
      // define a new functional component
      const WrappedComponent = ({ children, ...props}) => {
        ...
        return (
          <PassedComponent {...props}>
            {children.split("").reverse().join("")}
          </PassedComponent>
        );
      }
    
      // return new wrapped component with reversed children
      return WrappedComponent;
    }