Home > Blockchain >  onClick event not working with option tag in React
onClick event not working with option tag in React

Time:06-11

onClick event not working with <option> tag. How to use onClick event with select option tag. Each option must be given a different parameter.

   async function localization(language) {
      localStorage.setItem("language", language);
   }

   useEffect(() => {
    localization(localStorage.getItem("language"));
   }, []);

    return(
      <select>
        <option onClick={() => localization("ru")}>
          <RussinFlagIcon /> Ru
        </option>
        <option onClick={() => localization("uz")}>
          <UzbekistanFlagIcon /> Uz
        </option>
        <option onClick={() => localization("en")}>
          <UKFlagIcon /> En
        </option>
      </select>
    )

CodePudding user response:

Use onChange instead, it's how you should be working when it comes to <select>. You can do something like this:

Notice value attribute on <option>. The selected option's value will be the value of the <select>.

return(
  <select onChange = {(e)=> localization(e.target.value)}>
    <option value = "ru">
      <RussinFlagIcon /> Ru
    </option>
    <option value= "uz">
      <UzbekistanFlagIcon /> Uz
    </option>
    <option value="en">
      <UKFlagIcon /> En
    </option>
  </select>
)

CodePudding user response:

Normally the select is used with a [form][1], then you should use the onChange callback:

const Select = () => {
  const handleChange = (e) => localStorage.setItem("language", e.target.value);

  return (
     <label>
  <select name="languages" onChange={handleChange}>
    <option onClick={() => localization("ru")}>
      <RussinFlagIcon /> Ru
    </option>
    <option onClick={() => localization("uz")}>
      <UzbekistanFlagIcon /> Uz
    </option>
    <option onClick={() => localization("en")}>
      <UKFlagIcon /> En
    </option>
  </select>
</label>
  );
};

Then some comments about your code:

  • Your async function localization does not have to be async if you don't have a Promise in it.
  • And your useEffect does not do much except store the language in the localStorage based on the localStorage value ... [1]: https://www.w3schools.com/TAGS/att_select_form.asp
  • Related