'React: Focus input on keyboard click (ctrl F / cmd F) instead of triggering Browser Search

Morning peeps, I am trying to focus a search input in my application when someone presses CTRL+F or CMD+F instead of triggering the browser's search, and I would like to ask if that's even possible. An implementation that I found online but doesn't work obviously is this:

  window.addEventListener('keydown', function (e) {
    if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
      if (document.getElementsById('search').not(':focus')) {
        e.preventDefault();
        console.log('Search is not in focus');
        document.getElementsById('search').focus();
      } else {
        console.log('Default action of CtrlF');
        return true;
      }
    }
  });

I have also tried to use the useRef() from React in order to reach the input and focus it afterwards, but couldn't make it work. Any hints, ideas, code snippets that could help me?



Solution 1:[1]

  1. change getElementsById to getElementById
  2. use document.activeElement to check current focus element (much better approach)

Try this:

window.addEventListener('keydown', function (e) {
  if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
    if (document.getElementById('search') !== document.activeElement) {
      e.preventDefault();
      console.log('Search is not in focus');
      document.getElementById('search').focus();
    } else {
      console.log('Default action of CtrlF');
      return true;
    }
  }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Technical Shubham