Supercool
Supercool

Reputation: 560

How to get value of selected option in a dropdown using React JS?

I'm trying to get the selected value of the dropdown using React Js.

It is giving the values but is giving the values randomly from the the options.

<select 
    name="category-select-1"
    class="form-select category-select" 
    id="category-select-1" 
    value={eventCategory} 
    onChange={handleEventCategory}>
    <option value={"default"}>Category</option>
    <option value={"meeting"}>Meeting</option>
    <option value={"workhours"}>Work Hours</option>
    <option value={"business"}>Business</option>
    <option value={"holiday"}>Holiday</option>
    <option value={"getTogether"}>Get-Together</option>
    <option value={"gifts"}>Gifts</option>
    <option value={"birthday"}>Birthday</option>
    <option value={"anniversary"}>Anniversary</option>
    <option value={"others"}>Others</option>
</select>

Here's how I'm trying to do it.

const [eventCategory, setEventCategory] = useState();

const handleEventCategory = (e)=>{
    setEventCategory(e.target.value);
    console.log(eventCategory);
}

What is wrong?

How do I get the value of a selected option in a dropdown using React JS?

Upvotes: 1

Views: 2132

Answers (2)

Raiyad Raad
Raiyad Raad

Reputation: 537

Your code looks fine.

const handleEventCategory = (e)=>{
    setEventCategory(e.target.value);
    console.log(eventCategory);
}

console.log(eventCategory);

As setState is asynchronous, eventCategory value is printed before the state is changed. If you add console.log below the handleEventCategory you will get right output.

Upvotes: 1

tomleb
tomleb

Reputation: 2525

Setting the state in React acts like an async function.
Meaning that the when you set the state and put a console.log right after it, it will likely run before the state has actually finished updating.

Which is why we have useEffect, a built-in React hook that activates a callback when one of it's dependencies have changed.

Example:

useEffect(() => {
   console.log(eventCategory)
   // Whatever else we want to do after the state has been updated.
}, [eventCategory])

This console.log will run only after the state has finished changing and a render has occurred.

  • Note: "eventCategory" in the example is interchangeable with whatever other state piece you're dealing with.

Check the documentation for more info about this.

Upvotes: 2

Related Questions