Home > Net >  How do I add onClick() on a Select Dropdown via React
How do I add onClick() on a Select Dropdown via React

Time:11-08

I'm trying to apply reactI18next on a project, normally you to toggle the language change you would create a button that would call the "changelanguage" function like this:

  const changeLanguage = (lng) => {
    i18n.changeLanguage(lng);
  }

<button onClick={() => changeLanguage('en')}>en</button>

However, I was wondering if it's possible to make something similar but In a dropdown fashion.

Is there a way to trigger an onClick via select or other means?

Thanks and I hope to hear you guys soon!

CodePudding user response:

Yes this is possible, you can add onChange event handler on Select tag such as

import { useState } from "react";

export default function App() {
  const [lang , setLang] = useState('en')

  function changeLanguage(event){
    // i18n.changeLanguage(event.target.value)
    setLang(event.target.value)
  }
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <p>{lang}</p>
      <select value={lang} onChange={changeLanguage}>
        <option value="en">English</option>
        <option value="fr">French</option>
      </select>
    </div>
  );
}

you can test on working sandbox Edit rough-field-7nygrx

  • Related