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

How to contain the focus lock fighting to a special div? #77

Open
lcswillems opened this issue Jan 14, 2025 · 3 comments
Open

How to contain the focus lock fighting to a special div? #77

lcswillems opened this issue Jan 14, 2025 · 3 comments

Comments

@lcswillems
Copy link

lcswillems commented Jan 14, 2025

Let's say I have the following code:

import ReactFocusLock from "react-focus-lock";

<div>
  <div id="frontier">
    <ReactFocusLock>
      <input id="input1" />
    </ReactFocusLock>
  </div>
  <div>
    <input id="input2" />
  </div>
</div>

If #input2 is focused, I don't want react-focus-lock to fight for focus as #input2 is outside of #frontier.

How to do something like this with react-focus-lock?

@lcswillems lcswillems changed the title How to contain the focus lock to a special div? How to contain the focus lock fighting to a special div? Jan 14, 2025
@lcswillems
Copy link
Author

This is the code I'm using to do what I was describing:

import { useState, useEffect, PropsWithChildren, useRef } from "react";
import ReactFocusLock from "react-focus-lock";

export function FocusLock({ children }: PropsWithChildren) {
  const ref = useRef<HTMLElement>(null);
  const [disabled, setDisabled] = useState(false);

  useEffect(() => {
    const handleFocusChange = ({ target }: FocusEvent) => {
      if (!(target instanceof Node)) return;
      const boundary = ref.current?.closest("[data-focus-lock-boundary]");
      setDisabled(!!boundary && !boundary.contains(target));
    };

    document.addEventListener("focusin", handleFocusChange);
    return () => {
      document.removeEventListener("focusin", handleFocusChange);
    };
  }, []);

  return (
    <ReactFocusLock ref={ref} disabled={disabled}>
      {children}
    </ReactFocusLock>
  );
}

@theKashey
Copy link
Owner

You want to contain focus inside for keyboard operations, but auto-disable it when you operate with any content outside the lock using mouse?

The code you've provided is the correct solution for this task and is almost exactly what focus-on does

@lcswillems
Copy link
Author

Hey @theKashey ! I didn't know this package.

I've checked the code. With FocusOn, how do I delimit until where the focus should be kept?

For example, I want my input to be focused while the focus is kept in a specific zone.

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

2 participants