2

I'm working on a web application using React and react-bootstrap, (in TypeScript). I want to make a dropdown menu in the Navbar to change the language of the page. I've got a list of langauges and applying map on the list to make <Dropdown.Item> like this:

const languageList = [
    {
        Id: "en",
        Language: "English"
    },
...
]
const [t, i18n] = useTranslation();
const [lang, setLang] = useState<string>();
useEffect(() => {
  i18n.changeLanguage(lang);
}, [lang, i18n]);

const handleClick = (lg: string) => {
    setLang(lg)
}
...
return (
  <Dropdown>
    <Dropdown.Toggle variant="outline-secondary" id="dropdown-basic">
       language
    </Dropdown.Toggle>
    <Dropdown.Menu>
       {languageList.map((item) => {
         return(
          <Dropdown.Item value={item.Id} onClick={handleClick(item.Id)>
            {item.Language}
          </Dropdown.Item>
         )
       })}
    </Dropdown.Menu>
  </Dropdown>
)

Without the onClick={handleClick(item.Id) in the <Dropdown.Item> tag, this code gives me a dropdown menu like this: enter image description here

However, when I add onClick, it gives me these errors:
Type 'void' is not assignable to type 'MouseEventHandler | undefined'.ts(2322)
and
Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

If anyone knows how to fix this, please help me.

1 Answer 1

2

This part is wrong

 <Dropdown.Item value={item.Id} onClick={handleClick(item.Id)>
     {item.Language}
 </Dropdown.Item>

Should be

 <Dropdown.Item value={item.Id} onClick={() => handleClick(item.Id)}>
     {item.Language}
 </Dropdown.Item>

At the moment you are trying to assign the result of the function as the onClick-handler. Either pass the variable without execution or create a anonymous function that runs your desired function. If you need to pass a parameter you have to use the latter.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.