How do I get SwitchTranition to work with CSSTransition with TypeScript

2k views Asked by At

So I have been using react-trasition-group to perform transition on different states of the same element and all is working fine there. The problem arises when there are multiple(two) elements to transition between. I am not sure how it works in the documentation but whenever I enter the key TypeScript goes crazy ans tells me that key cannot be boolean, which is completely understandable as key is something reserved by React to be used as a unique identifier for dynamically generated elements.

My attempt

const [trigger, setTrigger] = useState(false)

return(
  <SwitchTransition mode="out-in">
    <CSSTransition
      addEndListener={(node: HTMLElement, done: () => void) => {
        node.addEventListener("transitionend", done, false)
      }}
      classNames="myclass"
      key={trigger}
    >
      {trigger ? (
        <p>Render when true</p>
      ) : (
        <p>Render when false</p>
      )}
    </CSSTransition>
  </SwitchTransition>
)

The error that I am getting is due to the above written fact and I cannot find in the documantation how the SwitchTransition is supposed to work. Any help is appreciated.|

PS: I have checked the for similar issues on Github and Stackoverflow but apparently no one has com across this similar error before.

Edit: I guess I should have elaborated further since I have had 2 suggestions asking me to change the boolean to string. That is not my issue. My issue is that the transition itself is not working which arises due to the fact the react-transition-group for some reason wants a key as written in the documentation. I also noticed that addEndListener is causing issues as well.

1

There are 1 answers

1
gabrieltnishimura On

Yes, indeed the Typescript version has some differences. Here's a working version.

const [trigger, setTrigger] = useState(0);
const nodeRef = useRef<any>(null);
return(
  <div>
    <button onClick={() => setTrigger(trigger + 1)}>toggle</button>
    <SwitchTransition mode="out-in">
      <CSSTransition
        nodeRef={nodeRef}
        addEndListener={(done: () => void) => {
          nodeRef.current?.addEventListener("transitionend", done, false);
        }}
        classNames="myclass"
        key={trigger}
      >
        <div ref={nodeRef}>
            <p>{trigger}</p>
        </div>
      </CSSTransition>
    </SwitchTransition>
  </div>
)

The nodeRef is used to provide a element reference to the transitions component, preventing this error:

Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Transition which is inside StrictMode. Instead, add a ref directly to the element you want to reference.

See demo at: https://stackblitz.com/edit/react-ts-fcyubb?file=index.tsx