Skip to content
Advertisement

How to use the default value attribute of a select tag

Now im working on a small task with a select tag like this

       <select
            name="selectmedgroup"
            id="selectmedgroup"
            value={selectedGroupValue}
            onChange={filterOnSelectChange}
          >
            <option value="" defaultValue hidden>
              -Select Group-
            </option>
            <option value="a">A</option>
            <option value="b">B</option>
            <option value="c">C</option>
            <option value="d">D</option>
           
          </select>

I want to get the value on change. Here is my on change function and state

const [selectedGroupValue, setSelectedGroupValue] = useState();

  const filterOnSelectChange = (e) => {
    setSelectedGroupValue(e.target.value);
    console.log(selectedGroupValue);
  };

Everything seems to work fine but when I log out the selected option first if I choose A for the first time I get undefined on the logs. If I choose B I get A logged out. If I choose C I get B logged out.

I don’t think it’s my ordering that’s wrong. Remember I don’t want to have an initial value on the state because this will be just a selection that I will use to filter what the user sees on the page. So for the first time on the component mount, nothing should be filtered.

I have a feeling that the problem is the first Option tag with the -Select Group- . Is there any way I can avoid using that first options tag because it is just like a placeholder whose value I don’t need to be selected?

How can I get the correct values? Please help

Advertisement

Answer

Try to console your selectedGroupValue on useEffect hook , solve it like this

import React, { useState } from 'react';

const App = () => {
    const [selectedGroupValue, setSelectedGroupValue] = useState();

    const filterOnSelectChange = (e) => {
        setSelectedGroupValue(e.target.value);
    };
    React.useEffect(() => {
        console.log(selectedGroupValue);
    }, [selectedGroupValue]);

    return (
        <>
            <select
                name="selectmedgroup"
                id="selectmedgroup"
                value={selectedGroupValue}
                onChange={filterOnSelectChange}
            >
                <option value="" defaultValue hidden>
                    -Select Group-
                </option>
                <option value="a">A</option>
                <option value="b">B</option>
                <option value="c">C</option>
                <option value="d">D</option>
            </select>
        </>
    );
};

export default App;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement