0

I'm new to React and I can't figure out how I can call a function inside through onClick() on a map loop. Let me show you:

  const changeLang = lang => {
    i18n.changeLanguage(lang);
  };

I have this function who is responsible to get me languages like English or Portuguese. And what I'm trying to do with the following code is change the language depending on which menu item I choose from a menu. To do this I have the following code:

const languages = [
  {
    value: 'pt',
    label: 'Portuguese',

  },
  {
    value: 'en',
    label: 'English',
  }
];

...
{languages.map(option => (
    <MenuItem key={option.value} value={option.value} onClick={() => this.changeLang (option.value)}>
        {option.label}
    </MenuItem>
))}

The problem is that it can't enter in my function changeLang, so the language is not chosen, no effect at all. I've tried the console.log and I get nothing in return. I'm pretty sure the problem is on onClick={() => this.changeLang (option.value)}, but I can't figured out why. Can you help me?

Pedro Relvas
  • 678
  • 7
  • 19

3 Answers3

1

If this is functional component then remove this keyword and call directly changeLang function

languages.map(option => (
    <MenuItem key={option.value} value={option.value} onClick={() => changeLang(option.value)}>
        {option.label}
    </MenuItem>
))
A.K.
  • 547
  • 1
  • 7
  • 22
0

This is a functional component, so you need to call changeLang and not this.changeLang

Hamza El Aoutar
  • 5,292
  • 2
  • 17
  • 23
0

What kind of error do you see in your console?

I immediately see a possible issue with your changeLang : you are not returning anything from it. Arrow function have an implicit return only when not using braces syntax :

example of bugged function without return value

I also see this typo :

this.changeLang (option.value)

should be

this.changeLang(option.value)

No space between the function call and its arguments.

Maybe you can try these avenues of investigation, and / or post more details about your component.

Mathieu
  • 725
  • 5
  • 19