Change several events on onClick in React

I have two buttons for changing language created by the .map function. I also use i18next to change languages.

When clicked on a button corresponding to a certain language, I want not only the language of a page to change, but to change the styling of a button (e.g. make background white).

I have managed to do the following with useState, however, it changes the ctyling of two buttons simultaneously.

Code:

const languages = [
  {
    code: 'en',
    name: 'English',
    country_code: 'gb',
    emoji: '🇬🇧'
  },

  {
    code: 'uk',
    name: 'Українська',
    country_code: 'ua',
    emoji: '🇺🇦'
  }
]



const Langbar = () => {
  const { t, i18n } = useTranslation();
  const [isActive, setIsActive] = useState(false);

  const handleClick = () => {
    setIsActive(current => !current);
  };
  return (
    <div className='container langbar_container'>
      <h3>{t('language')}</h3>
    {languages.map(({code, emoji}) => (
            <button 
            onClick={() => {i18next.changeLanguage(code); handleClick}}
            className="btn btn-secondary langbar_btn"
            style={{
              background: isActive ? 'white' : ''}
            }>
              <span>{emoji}</span>
            </button>
    ))}
</div>
  )
}

>Solution :

you can try this

const Langbar = () => {
  const { t, i18n } = useTranslation();
  const [isLangCode, setLangCode] = useState("");

  const handleClick = () => {
    setLanCode(current => !current);
  };
  return (
    <div className='container langbar_container'>
      <h3>{t('language')}</h3>
    {languages.map(({code, emoji}) => (
            <button 
            onClick={() => {i18next.changeLanguage(code); handleClick}}
            className="btn btn-secondary langbar_btn"
            style={{
              background: isLangCode == code ? 'white' : ''}
            }>
              <span>{emoji}</span>
            </button>
    ))}
</div>
  )
}

Leave a Reply