1

In my React Native app, I'm using the library, react-native-card-flip.

In the class component, I use it as follows:

<CardFlip style={styles.cardContainer} ref={(card) => this.card = card} >
  <TouchableOpacity style={styles.card} onPress={() => this.card.jiggle({ count: 2, duration: 100, progress: 0.05 })} ><Text>AB</Text></TouchableOpacity>
  <TouchableOpacity style={styles.card} onPress={() => this.card.flip()} ><Text>CD</Text></TouchableOpacity>
</CardFlip>

However, if I put the same thing in a functional component, I get an error about the 'ref'.

Undefined is not an object. Evaluating _this.card = card.

Something wrong with ref in the functional component. How can I correct this? Can you please help?

3
  • you have to use useRef reactjs.org/docs/hooks-reference.html#useref Commented Mar 30, 2021 at 10:55
  • I tried this. The error goes away, but the CardFlip component just doesn't render. Commented Mar 30, 2021 at 11:11
  • 1
    I'll add an answer. Commented Mar 30, 2021 at 11:28

1 Answer 1

2

In order to use the ref in the functional component, you have to:

  1. Create a ref using useRef;

const card = useRef(null);

  1. Assign this ref to the cardFlip

CardFlip ref={card}

  1. Do actions on it using the current property of the ref.

card.current.jiggle(...).

Depending on how you've configured your CardFlip, (if the jiggle and flip are functions and CardFlip is a functional component) you may need to use forwardRef and useImperativeHandle. Try out this answer as is, if it doesn't work then I'll modify the answer.

Sign up to request clarification or add additional context in comments.

2 Comments

I've tried it in exactly the same way. It doesn't work. The component CardFlip is coming from this library - npmjs.com/package/react-native-card-flip
Can you log card.current? Which methods does it provide?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.