Home > Back-end >  How to get value of selected option in a dropdown using React Js?
How to get value of selected option in a dropdown using React Js?

Time:09-20

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

It is giving the values but it's giving the wrong values

Please find my code below.

<select 
    name="category-select-1"
     
    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);
}

It is giving the values randomly from the the options. Please help me figure this out. Thanks

CodePudding user response:

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.

CodePudding user response:

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.

  • Related