javascriptreactjshigher-order-functionsreact-hoc

Why is the callback function not working in the HOC component?


I'm passing the state (setActive) to the ButtonsOur component. Further, through the callback, I pass setActive to the HOC, but I get this error "Uncaught TypeError: setActive is not a function". Why it doesn't work, and how i can fix this? In ButtonsOur component I am passing setActive from parent component via props

This is my ButtonsOur component

import HOC from '../../../hoc/HocPopUp';

 function ButtonsOur({ setActive, open }) {
  return (
   <div className="base__routes__button">
  <Buttons className="base__button__moreInf open-popup-exc" Click={open(setActive)}>Докладніше</Buttons>
  <Buttons className="base__button__moreInf open-popu p-exc" Click={open(setActive)}>Забронювати</Buttons>
</div>
 );
}

export default HOC(ButtonsOur);

And this is my HOC

 const HOC = (Component) => {
 function HandleChange(props) {
  function open(setActive) {
    setActive(true);
  }

 function close(setActive) {
   setActive(false);
 }
return (
  <Component
    close={() => close}
    open={() => open}
    // eslint-disable-next-line react/jsx-props-no-spreading
    {...props}
  />
  );
  }
  return HandleChange;
   };

export default HOC; 

Solution

  • The HOC isn't reading setActive, open from the passed props.

    Also you need to pass the original props early on, and have the props in the HOC override them where necessary.

    
    const HOC = (Component) => {
      function HandleChange(originalProps) {
        function open(setActive) {
          originalProps.setActive(true);
        }
    
        function close(setActive) {
          originalProps.setActive(false);
        }
        return (
          <Component
            // eslint-disable-next-line react/jsx-props-no-spreading
            {...originalProps}
            close={close}
            open={open}
          />
        );
      }
      return HandleChange;
    };