Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading