Skip to content
This repository has been archived by the owner on Oct 4, 2021. It is now read-only.

Why using Context and custom id instead of register function ? #28

Closed
LoiKos opened this issue Sep 22, 2020 · 2 comments
Closed

Why using Context and custom id instead of register function ? #28

LoiKos opened this issue Sep 22, 2020 · 2 comments

Comments

@LoiKos
Copy link

LoiKos commented Sep 22, 2020

I was doing research about 'Flip Animation' when i find your great article on this subject.

I build my own hook to do a really simple flip on row re-order but i was wondering why do you use context and id instead of a register function based on ref ? Is it to keep support for Class component ?

function useFlipAnimation(deps, options) {
  const elements = React.useRef(new Map()).current

  const { duration = DEFAULT_DURATION } = options

  const register = useCallback(
    (elRef) => {
      if (elRef) {
        const initialRect = elRef.getBoundingClientRect()
        elements.set(elRef.id, { el: elRef, rect: initialRect })
      }
    },
    [elements]
  )

  React.useLayoutEffect(() => {
    for (const [key, value] of elements) {
      const cachedRect = value.rect

      if (cachedRect) {
        const nextRect = value.el.getBoundingClientRect()

        const translateY = cachedRect.y - nextRect.y

        elements.set(key, { ...value, rect: nextRect })

        value.el.animate(
          [
            { transform: `translateY(${translateY}px)` },
            { transform: `translateY(0px)` },
          ],
          duration
        )
      }
    }
  }, [deps, duration, elements])

  return { register }
}

// E.g
const TestComponent = function(props){
   const elements = [..list of elements goes here...]
   const {register} = useFlipAnimation()

  return elements.map( element => 
<div ref={register}>...implementation details </div>)
}
@jlkiri
Copy link
Owner

jlkiri commented Sep 23, 2020

Context is to make element cache available to other parts of the library, such as AnimateInOut which might need to know whether an item is being animated or not, for example.

In previous version there was a case where I think refs would not work, but probably not anymore.
Actually I'm (very slowly) working on the next version, and I will use refs there.

@LoiKos
Copy link
Author

LoiKos commented Sep 23, 2020

Thanks for your quick answer. I'm asking this mainly for educational purpose and i look to the lib code and it looks amazing ! Great job with this lib.

@LoiKos LoiKos closed this as completed Sep 23, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants