Thursday, 31 December 2020

Blur Material UI Select component on the onChange event

By default MaterialUI's Select component leaves itself focused after selecting an option. This behaviour can be seen in all their examples in their docs

I would like the element to blur once something is selected. Here is what my code currently looks like:

const App = () => {
    const [selectedValue, setSelectedValue] = useState('')

    const selectElement = useRef(null);

  return (
        <Select
            native
            ref={selectElement}
            value={selectedValue}
            onChange={(evt) => {
                setSelectedValue(evt.target.value)

                // Attempt at blurring the element upon selection using the useRef:
                selectElement.current.blur(); // Nothing happens

                // Attempt at blurring the element upon selection using activeElement:
                document.activeElement.blur(); // Get Error: "Property 'blur' does not exist on type 'Element'."
            }}
        >
            <option value='option 1'>Option 1</option>
            <option value='option 2'>Option 2</option>
            <option value='option 3'>Option 3</option>
        </Select>
  );
};

As you can see in the code, I've tried to do this with two different methods I've found:

  • Through useRef(): this does nothing, no errors or anything, but does not blur my element

  • Through the document.activeElement: this gives me an error, apparently property blur does not exist on type element.

What is the proper method of blurring my Select component upon selecting an option?



from Blur Material UI Select component on the onChange event

No comments:

Post a Comment