Skip to content
Advertisement

Can’t focus on object before it is hidden (react)

I have this input that when focused opens up a select.

The behavior I want could be achieved with a simple select but I wish to further add functionalities that a simple select does not allow. Simply put when you have the ‘box’ focused, you can view the options, when you don’t you cannot.

I tried to implement this logic using a state that checks if the parent div where the select and the input is focused. Clicking the input displays the options as expected, however when I try to select an option from the list, before I can select it, the select gets hidden and I can’t choose anything.

Demo

Is there another approach for this?

Advertisement

Answer

The trouble is that another focusable element (the select) receives focus. You can’t avoid that, but you can change how you react to that: you need to check whether the element causing the blur is a descendant of your div. If it is, you don’t need to close your select box.

Change your onBlur handler to this:

const onBlur = ({ currentTarget, relatedTarget }) => {
    if (!currentTarget.contains(relatedTarget)) {
        setMenuActive(false);
    }
};

Forked demo. Note that I also changed your state to a simple boolean instead of an object.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement