Search code examples
react-nativereact-native-animatable

How same thing can be done in functional component?


I' getting the output in class-based component, but I want to know how the same thing can be done in functional component

class Apps extends React.Component {
  handleViewRef = ref => this.view = ref;

  bounce = () => this.view.bounce(800)

  render() {
    return (
      <View style={{margin:60}}>
      <TouchableWithoutFeedback onPress={this.bounce}>
        <Animatable.View ref={this.handleViewRef}>
          <Text>Bounce me!</Text>
        </Animatable.View>
      </TouchableWithoutFeedback>
      </View>
    );
  }
}

Solution

  • You'll need to use hooks to achieve this:

    const App = ()=>{
      const const viewRef = useRef(null);
      const bounce = useCallback(() => {
        if (viewRef.current) {
          viewRef.current.bounce(800)
        }, [viewRef]
      );
        return (
          <View style={styles.container}>
          <TouchableWithoutFeedback onPress={bounce} style={styles.container}>
             <Button ref={viewRef} rounded warning>
                <Text>Warning</Text>
              </Button>
          </TouchableWithoutFeedback>
          <Apps/>
          </View>
        );
    }
    

    The useCallback is not strictly necessary but will prevent re-creating the bounce callback on every render. See https://reactjs.org/docs/hooks-reference.html#useref and https://reactjs.org/docs/hooks-reference.html#usecallback