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:
I have no idea why I get this error since I do not use classes here Thanks for help
There are a few things to note here
useAxisTranslate
which is meant to be a custom hook within withUseAxisTranslate
which is not component but a function returning another function.useSelector
and useTranslation
in the custom hook inside of the the returned function which again violates the rulesThe 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
];
};