kb_
kb_

Reputation: 187

How to updated dropdown selection to "selected" onClick

In this React app, I have a dropdown menu to select between different options. When an option is clicked, it sets that option's value to the localStorage. However, once i move to a different page, the dropdown doesn't show the value that was selected, it defaults to the first option. I am guessing that I need to add functionality that when an option is selected, the item get's updated to have 'selected' in the element. How would i go about doing that?

This is the code:

<select onChange={(e) => window.localStorage.setItem('language', e.target.value)}>
  <option onClick={() => window.localStorage.setItem('language', 'en')}>en</option>
  <option onClick={() => window.localStorage.setItem('language', 'es')}>es</option>
</select>

Upvotes: 0

Views: 179

Answers (2)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20954

You could create a custom hook which controls the storage of the language with a useState hook.

const useLanguageStorage = () => {
  const [ language, setLanguage ] = useState(localStorage.getItem('language'))

  useEffect(() => {
    localStorage.setItem('language', language)
  }, [language])

  return [ language, setLanguage ]
}

Then use that hook in your component to set the new language whenever the onChange handler is called.

You can set the default selected value with the value property.

const DropDownComponent = () => {
  const [ language, setLanguage ] = useLanguageStorage()

  const handleChange = event => {
    setLanguage(event.target.value)
  }

  return (
    <select onChange={handleChange} value={language}>
      <option value={'en'}>en</option>
      <option value={'es'}>es</option>
    </select>
  )
}

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371193

Change the <select> to a controlled component. On change, set state to the target's value as well as updating localStorage, and then render the <select> with a value of the state that was set:

const [value, setValue] = useState(localStorage.getItem('language'));
<select
  value={value}
  onChange={(e) => {
    window.localStorage.setItem('language', e.target.value);
    setValue(e.target.value);
  }}
>
  <option>en</option>
  <option>es</option>
</select>

It may or may not be useful here, but a more general way to set localStorage when a particular state gets updated is to use useEffect, instead of putting the functionality next to each setter:

useEffect(
  () => {
    window.localStorage.setItem('language', value);
  },
  [value]
);

Upvotes: 1

Related Questions