0

I have a basic react functional component and I bind an array in which there are strings to be localized. Is there any other way to do it? I am trying as below and it says "Invalid Hook Call"

import { useIntl } from "react-intl";

const NavBasicExample: React.FunctionComponent = () => {  
  return (
      <Nav               
        groups={navLinkGroups}        
      />
    </div>
  );
};



const navLinkGroups: INavLinkGroup[] = [
  {
    name: getFormattedString(Strings.details),//This fails and says invalidHookCall
    links: [{ name: Strings.appDetails, url: "" }]
  },
  {
    name: Strings.capabilities,
    links: [
      { name: Strings.tabs},
      { name: Strings.bots}
    ]
  }
];



const getFormattedString = (inputString: string) => {
  const intl = useIntl(); //This fails.
  return intl.formatMessage({ id: "details", defaultMessage: "Login });
};
Diksha Mundhra
  • 121
  • 2
  • 12

1 Answers1

1

The problem is that you are calling a Hook from a non-react function. You are not allowed to do that. Try moving the "navLinkGroups" into the "NavBasicExample" and it should work

import { useIntl } from "react-intl";

const NavBasicExample: React.FunctionComponent = () => {  
  const intl = useIntl();
  

  const navLinkGroups: INavLinkGroup[] = [
    {
      name: getFormattedString(Strings.details),
      links: [{ name: Strings.appDetails, url: "" }]
    },
    {
      name: Strings.capabilities,
      links: [
        { name: Strings.tabs},
        { name: Strings.bots}
      ]
    }
  ];
  
  const getFormattedString = (inputString: string) => {
    return intl.formatMessage({ id: "details", defaultMessage: "Login" });
  };

  return (
      <Nav               
        groups={navLinkGroups}        
      />
    </div>
  );


};
Andrea
  • 1,286
  • 6
  • 18
  • How to keep the array out of the function and make it work? Just for better code readability. – Diksha Mundhra Aug 12 '20 at 19:21
  • @DikshaMundhra You'd want to create the array in a slightly different way. E.g. const MyArray=[{ name:Strings.details, links: [{ name: Strings.appDetails, url: "" }] }]; and then inside the class using it you would have const MyUsableArray=MyArray.map((item)=> ({...item, name: getFormattedString(item.name)}) ) – Andrea Aug 13 '20 at 12:58