Home > Back-end >  Default value of KeyboardEvent with useState
Default value of KeyboardEvent with useState

Time:12-18

I'm listening to keydown in document from a React component:

import { useState, useEffect } from "react";
import { render } from "react-dom";

function App() {
  const [keyEvent, setKeyEvent] = useState<KeyboardEvent>()

  function handleDocumentKeyDown(event: any) {
        setKeyEvent(event)
    }

    useEffect(() => {
        // Can't use React onKeyDown in input because the event won't trigger outside of the input
        document.addEventListener('keydown', handleDocumentKeyDown)

        return () => {
            document.removeEventListener('keydown', handleDocumentKeyDown)
        }
    }, [])

  return (
    <div>
    </div>
  );
}

const rootElement = document.getElementById("root")
render(<App />, rootElement)

I don't know what default value to give to keyEvent.

useState<KeyboardEvent>({}) throws this TypeScript error:

Argument of type '{}' is not assignable to parameter of type 'KeyboardEvent | (() => KeyboardEvent)'.

useState<KeyboardEvent>(null) throws this TypeScript error:

Argument of type 'null' is not assignable to parameter of type 'KeyboardEvent | (() => KeyboardEvent)'.ts(2345)

CodePudding user response:

Generally you can use React.KeyboardEvent<Element>, but for document handlers React.KeyboardEvent<Document> should works

CodePudding user response:

You can try this:

const [keyEvent, setKeyEvent] = useState<KeyboardEvent | null>(null);

It should work, and I think it's quite explicit and clear. Then, if you'll need to set it back to null somewhere in the future, you'd also won't face any type errors.

  • Related