Jan Cziżikow
Jan Cziżikow

Reputation: 613

Typing out react-transition-group handlers in TypeScript

I'm trying to type out handlers that are passed to some of the react-transition-group components, such as addEndListener in <CSSTransition />. But I cannot find a way to type it properly and avoid TypeScript errors.

link to a codesandbox with the type error.

Eg.:

<CSSTransition
  // TypeScript Error on next line: 
    addEndListener={(node: HTMLElement, done: () => void) => {
      node.addEventListener("transitionend", done, false);
    }}
    classNames="fade"
  >
  <div className="button-container">
    <Button onClick={() => setState((state) => !state)}>
      {state ? "Hello, world!" : "Goodbye, world!"}
    </Button>
  </div>
</CSSTransition>

Versions of react, react-transition-group and their @types equivalents:

"react": "^16.13.1"
"react-transition-group": "^4.4.1"
"@types/react": "^16.9.43"
"@types/react-transition-group": "^4.4.0"

Upvotes: 5

Views: 3535

Answers (1)

concat
concat

Reputation: 3187

You need to specify the generic parameter to CSSTransition, which decides the type of the callback based on if that ref is HTMLElement or not by using conditional types. So in your case (this requires typescript >= 2.9):

<CSSTransition<undefined>
    addEndListener={(node: HTMLElement, done: () => void) => {
      node.addEventListener("transitionend", done, false);
    }}
    classNames="fade"
  >
  <div className="button-container">
    <Button onClick={() => setState((state) => !state)}>
      {state ? "Hello, world!" : "Goodbye, world!"}
    </Button>
  </div>
</CSSTransition>

Upvotes: 9

Related Questions