Can't set focus on the lowerJaw button

In, feat(client): refactor lower-jaw elements to jsx.element by Sboonny · Pull Request #49015 · freeCodeCamp/freeCodeCamp (github.com), I am trying to refactor the element to JSX.element, because:

  • jsx.element has its own state, which means when the camper interacts with the component, the parent doesn’t re-render.
  • when the parent state changes, it doesn’t need to render the elements again, because it remembers the state of jsx.element.
  • It’s way easier to understand and read.

But there is a test failing because the browser doesn’t focus on the “Submit” button, when campers press “Ctrl + enter”, here is a gif for it.

Can't-focus


Attempts

  • I have attempted to use focus::visible by using .btn::focus-visible selector, and let the browser handle this, but with no luck.

https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-visible

  • I have swapped the createRef, to useRef hoping that I am missing something and to be honest testing my luck, but same as before no luck
const submitButtonRef = useRef<HTMLButtonElement>(null);
...
  useEffect(() => {
    if (challengeIsCompleted && !isEditorInFocus) {
      submitButtonRef?.current?.focus();
    }
...
      <LowerJawButtons
        ref={submitButtonRef}
      />

useRef (reactjs.org)

I am wondering, what am I missing that stops the browser from focusing on the button?


Additional context:

console.log(submitButtonRef?.current?.focus()); will result in undefinded and not focusEvent like I hoped.

it('checks hotkeys when instruction is focused', () => {
    cy.reload();
    cy.focused().type('{end}{enter}<meta charset="UTF-8" />');
    cy.get(selectors.instructionContainer)
      .click('topRight')
      .trigger('keydown', { ctrlKey: true, keyCode: 13 }); // keyCode : 13 enter key
    cy.get(selectors.lowerJawButton).should('be.focused');
  });

I would say that this test is not correct. The focus should not be on the button after using the Ctrl + Enter hotkey combo if the focus wasn’t already on the button when the hotkeys were pressed. Moving focus unnecessarily can be confusing for screen reader users and potentially annoying for all keyboard users.

But I do see that moving focus like this does currently happen on production. Seeing as your PR does not have this behavior, but rather leaves the focus where it is, I think your PR is the correct implementation and either we should get rid of this test or change it to make sure that the focus hasn’t changed.

1 Like