Skip to content

Commit

Permalink
Fix calling getBoundingClientRect on null (#5462)
Browse files Browse the repository at this point in the history
## Summary

In implementation of web layout animations I used
`getSnapshotBeforeUpdate` to get position of element before its
re-render. However, this function lacks checks for platform and whether
component is null or not.

## Test plan

Tested on provided repro

<details>
<summary> Code from issue </summary>

```jsx
import React, {useRef, useState} from 'react'
import {StyleSheet, Text, TouchableOpacity, View, ViewStyle} from 'react-native'
import Animated from "react-native-reanimated"
import FastImage from "react-native-fast-image"

export const ReanimatedFastImage = Animated.createAnimatedComponent(FastImage)
const App = () => {

  const [value, setValue] = useState(false)
  const cardImageRef = useRef<any>(null)

  const onPress = () => {
    setValue(!value)
  }

  return (
    <View style={styles.container}>
      <ReanimatedFastImage ref={cardImageRef} />
      {value ? <View /> : null}
      <TouchableOpacity onPress={onPress} style={styles.buttonStyle}>
        <Text>Toggle Set State</Text>
      </TouchableOpacity>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
    alignItems: 'center'
  } as ViewStyle,
  buttonStyle: {
    backgroundColor: 'grey',
    width: 200,
    height: 50,
    marginVertical: 20,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default App

```

</details>
  • Loading branch information
m-bert committed Dec 4, 2023
1 parent c6ddd55 commit 15717e7
Showing 1 changed file with 2 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/createAnimatedComponent/createAnimatedComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,8 @@ export function createAnimatedComponent(
// and later on, in componentDidUpdate, calculate translation for layout transition.
getSnapshotBeforeUpdate() {
if (
(this._component as HTMLElement).getBoundingClientRect !== undefined
IS_WEB &&
(this._component as HTMLElement)?.getBoundingClientRect !== undefined
) {
return (this._component as HTMLElement).getBoundingClientRect();
}
Expand Down

0 comments on commit 15717e7

Please sign in to comment.