reactjsreact-hooksreact-hoc

Use react hook in HOC with passed params


I am trying to create HOC and use custom react hook inside. Also in order to use hook I need to pass paras to HOC, but I get error for use hook only in function body. My HOC is:

export const withUseAxisTranslate = (props) => {
  const [t] = useAxisTranslate(props.namespace);
  return (WrappedComponent) => (moreProps) => <WrappedComponent {...moreProps} t={t} />;
};

My useAxisTranslate looks like:

import { useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';

//This one is behave like regular i18 translate
//It returns like t() in array function and use axis name in order to find specific key by axis name
const useAxisTranslate = (namespace) => {
  return [
    (stringToTranslate) => {
      const axisName = useSelector((state) => state.axisConfig.axis.name.toLowerCase());
      const [t] = useTranslation(namespace);
      return t(`${axisName}.${stringToTranslate}`);
    },
  ];
};

export default useAxisTranslate;

My call to it is:

compose(
  withWidth(),
  withUseAxisTranslate({ namespace: 'header' }),
)(MyComponent);

The error I got is:

enter image description here

I have no idea why I get this error since I do not use classes here Thanks for help


Solution

  • There are a few things to note here

    The solution here is to correct both the things like below

    export const withUseAxisTranslate = (props) => {
      return (WrappedComponent) => (moreProps) => {
            const [t] = useAxisTranslate(props.namespace);
            return <WrappedComponent {...moreProps} t={t} />
      }
    };
    

    and useAxisTranslate as

    const useAxisTranslate = (namespace) => {
      const axisName = useSelector((state) => state.axisConfig.axis.name.toLowerCase());
      const [t] = useTranslation(namespace);
      const translateFunction = (stringToTranslate) => {
          return t(`${axisName}.${stringToTranslate}`);
      };
      return [
        translateFunction
      ];
    };