Aakash Thakur
Aakash Thakur

Reputation: 3895

Ref null inside Popover

I am trying to autofocus an input element on opening of a popover. Here is the sandbox for it: https://codesandbox.io/s/green-bash-x6bj4?file=/src/App.js

Issue here is that the current property is always null on ref. Is this a case where forwardRef might help? I am not much aware of it so posting it.

Any help is much appreciated.

Upvotes: 1

Views: 1761

Answers (3)

J.T
J.T

Reputation: 579

You could simple add a callback after the setState, like this:

    this.setState(
      {
        anchorEl: e.currentTarget,
        isPopoverOpen: true,
      },
      () => {
        setTimeout(() => {
          if (this.inputRef.current) {
            return this.inputRef.current.focus();
          }

          return null;
        }, 200);
      }
    );
  };

With the timeout you can secure that the popover is mounted and the input is visible, so the input will be focused when the timeout is passed. Using async/await is more for promises.

Upvotes: 1

keikai
keikai

Reputation: 15166

Since you control the open via state, which is async, when the inputRef tries to get the element, the state hasn't been updated, and the Proper children haven't been created.

You can add an async/await to the setState to make it works.

const handleClick = async event => {
  await setAnchorEl(event.currentTarget);
  inputRef.current.focus();
};

Edit heuristic-allen-hubry

enter image description here

Upvotes: 1

HermitCrab
HermitCrab

Reputation: 3274

No need to use a ref for that, just add autoFocus to your input:

<input autoFocus placeholder="search" />

Upvotes: 1

Related Questions