For localization lang, I created a drropdown with two options Eng and Th (Thai). But While fetching the data, four options are showing for the same.
For example, if I select Thai, then 3 Thai options, and one Eng is showing, and vice versa for Eng also.As shown in figure

please help to figure it out.
My Selection code as follows:
<select
name="EN"
id="EN"
onChange={(e) => {
localStorage.setItem("lang", e.target.value);
window.location.reload(false);
}}
>
{localStorage.getItem("lang") !== null ? (
<option selected={localStorage.getItem("lang")}>
{localStorage.getItem("lang").toUpperCase()}
</option>
) : null}
<option value="en">EN</option>
<option value="th">TH</option>
</select>
The first one showing is the selected option you had wrote here:
<option selected={localStorage.getItem("lang")}>
{localStorage.getItem("lang").toUpperCase()}
</option>
The second one when you display the dropdown, is your selected one and I believe that's how the select element works by default. I don't know how to change that behavior.
Now, the third and fourth options are the ones you wrote here:
<option value="en">EN</option>
<option value="th">TH</option>
I would do something like:
{(localStorage.getItem("lang")) === en ?
<option value="th">TH</option> :
<option value="en">EN</option>)}
That way, you would only have the selected one, and the not selected one as options. The way you have wrote the code it will always show an EN and a TH option regardless the selected option.
Edit: after looking the code again, I don't understand why you fetch the selected lang as an option. It would be easier to just to:
<select
name="EN"
id="EN"
onChange={(e) => {
localStorage.setItem("lang", e.target.value);
window.location.reload(false);
}}
>
<option selected value="en">EN</option>
<option value="th">TH</option>
</select>
Also, i would rename the "name" and "id" of the select, to something like langSelector or anything like that and not having it related to a specific option, because that could change depending on the user decision.
If you really want to just have two options (actually one), I would look at this answer as a guide and make the placeholder a conditional based on the "lang" stored on your local storage, and the option would be a conditional too, like the example I already gave:
https://stackoverflow.com/a/30525521/14492009
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With