FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Easy

Use Focus

10mins

Implement a function useFocus() that allows focusing on an HTML element programmatically.

The function should:

  • Return an object containing a ref property to attach to an element.
  • Return a focus() method that focuses the attached element when called.
  • Ensure calling focus() on an unmounted element does not throw an error.

Examples

const { ref, focus } = useFocus(); const input = document.createElement('input'); ref.current = input; focus(); console.log(document.activeElement === input); // true

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests