0

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>
    );
  }
}
learner62
  • 520
  • 3
  • 10
  • 26
  • I want when a user press button animation should happen, the same thing I have done using class component it is working but I want using functional component please refer this link same thing I have done in a class component [link] **(https://snack.expo.io/@sushil62/55950b)** @Tim – learner62 Sep 12 '19 at 06:52

1 Answers1

1

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

azundo
  • 5,902
  • 1
  • 14
  • 21
  • Hi,@azundo can you check this [link](https://snack.expo.io/@sushil62/55950b) what is the issue with it – learner62 Sep 12 '19 at 07:10
  • You're using a NativeBase `Button` in the `App` component which doesn't have a `bounce` method. If you swap the `Button` for the same `Animatable.View` you're using in the `Apps` component you'll see that the hooks code works as expected. – azundo Sep 12 '19 at 07:15