AlexBerd
AlexBerd

Reputation: 1504

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

Upvotes: 0

Views: 1710

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 282030

There are a few things to note here

  • You are trying to use useAxisTranslate which is meant to be a custom hook within withUseAxisTranslate which is not component but a function returning another function.
  • You are using useSelector and useTranslation in the custom hook inside of the the returned function which again violates the rules

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
  ];
};

Upvotes: 3

euvs
euvs

Reputation: 1645

Try moving the useAxisTranslate hook inside the body of the component, like so

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

Upvotes: 0

Related Questions