I am currently working on a project where I need to track the position of a view that is being moved with a pan responder. Although I am using the onLayout prop to access the width, height, x and y positions, it seems to only run during the first render. Any suggestions on how to handle this issue?
Below is the code snippet:
import React, { useState, useRef } from "react";
import {
View,
Animated,
PanResponder,
Dimensions,
StyleSheet,
} from "react-native";
const WINDOW_HEIGHT = Dimensions.get("window").height;
export default function Cropper({ photo }) {
const [height, setHeight] = useState(WINDOW_HEIGHT / 2); // For future use
const pan = useRef(new Animated.ValueXY()).current;
const panResponder = useRef(
PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: Animated.event([null, { dy: pan.y }]),
onPanResponderRelease: () => {
pan.flattenOffset();
},
})
).current;
const onLayout = (event) => {
const {
nativeEvent: { layout },
} = event;
// Code logic for recalculating top and bottom views' height goes here
};
const panStyle = {
transform: pan.getTranslateTransform(),
};
return (
<View style={styles.container}>
<View style={styles.blurView} />
<Animated.View
onLayout={(event) => onLayout(event)}
{...panResponder.panHandlers}
style={[
styles.cropper,
panStyle,
{
height: height,
},
]}
/>
<View style={styles.blurView} />
<View style={styles.bottomButtonsContainer}></View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
blurView: {
flex: 1,
width: "100%",
backgroundColor: "rgba(0, 0, 0, .9)",
},
cropper: {
width: "100%",
backgroundColor: "red",
},
bottomButtonsContainer: {
position: "absolute",
bottom: 0,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
width: "100%",
height: 120,
},
});
The goal is to determine the middle view position as the user interacts with it, and then dynamically adjust the heights of the top and bottom views accordingly.