Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change focus to input tag #3

Open
muh-hizbe opened this issue Oct 31, 2021 · 2 comments
Open

Change focus to input tag #3

muh-hizbe opened this issue Oct 31, 2021 · 2 comments

Comments

@muh-hizbe
Copy link

I need change a focus to input tag when div with rti--container class clicked. I think that's more better .

@DanWebb
Copy link

DanWebb commented Oct 9, 2022

A workaround could be to wrap the component in another element, then watch the click event on it to focus the inner input...

    <div
      id={id}
      onClick={() => (document.querySelector(`#${id} .rti--input`) as HTMLInputElement).focus()}
   >
      <TagsInput
        value={selected}
        onChange={setSelected}
      />
   </div>

Ideally, this lib would expose the ref from the inner input for this kind of thing.

@bradley
Copy link

bradley commented Aug 24, 2023

Here is a fully working (as Id expect UX-wise, anyway) solution. It uses onMouseDown instead of onClick because onMouseDown is fired before any blur event, so will allow the input to always retain focus. YMMV but Ive logged the interaction events and it all seems to work as expected:

const EmailsInput = () => {
  const [selected, setSelected] = useState([]);

  const wrapperRef = useRef(null);

  const handleWrapperClick = e => {
    const wrapperEl = wrapperRef.current;

    if (!wrapperEl) {
      return;
    }

    const rtiContainerEl = wrapperEl.querySelector(".rti--container");
    const rtiInputEl = wrapperEl.querySelector(".rti--input");

    if (!rtiInputEl) {
      return;
    }

    // Prevent default so that the input doesn't lose focus, if the mousedown
    // event occured on the RTI container el wrapped by our outer wrapper el.
    if (e.target === rtiContainerEl) {
      e.preventDefault();
    }

    // Focus the input. If it was previously focused it will retain focus.
    rtiInputEl.focus();
  };

  return (
    <div ref={wrapperRef} onMouseDown={handleWrapperClick}>
      <TagsInput
        value={selected}
        onChange={setSelected}
        name="Email Addresses"
        placeHolder="Add Email Address..."
        isEditOnRemove={true}
        separators={
          [
            "Enter",
            "Tab",
            ",",
            " "
          ]
        }
      />
      <div className="flex flex-row justify-end text-xs text-zinc-500 mt-2">
        <em>Press "return" or "enter" to add new emails.</em>
      </div>
    </div>
  );
};

Bless.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants