3

Im using this package to add credit cards to my app, how would you åccess the refs as in the example when using this in a functional component?

This is how they show to update values:

this.refs.CCInput.setValues({ number: "4242" });

I don't know how to access that inside a functional component?

This is my component to Edit a card, and I want to add the current values to the inputs.

import React, {useContext, useState, useRef} from 'react';
import {Text, View, StyleSheet, TouchableOpacity} from 'react-native';
import {CreditCardInput} from 'react-native-input-credit-card';

import Store from '../../store/context';

const styles = StyleSheet.create({

});

export default function EditCard(props) {
  const {navigate} = props.navigation;
  const {cardNumber} = props.navigation.state.params;
  const {state, dispatch} = useContext(Store);
  const [card, setCard] = useState(
    state.cards.find(card => {
      return card.values.number === cardNumber;
    }),
  );
  const _onChange = form => {
    if (form.valid) {
      setCard(form);
    }
  };
  const updateCard = () => {
    dispatch({
      type: 'ADD_CARD',
      payload: card,
    });
    navigate.goBack();
  };
  return (
    <View style={styles.container}>
      <CreditCardInput
        validColor={'#47B278'}
        invalidColor={'#E23C3C'}
        placeholderColor={'#efefef'}
        onChange={_onChange}
        requiresName
      />
      <TouchableOpacity
        style={
          card
            ? card.valid
              ? styles.button
              : styles.buttonDisabled
            : styles.buttonDisabled
        }
        disabled={card ? (card.valid ? false : true) : true}
        onPress={updateCard}>
        <Text style={styles.buttonText}>Update Credit Card</Text>
      </TouchableOpacity>
    </View>
  );
}

1 Answer 1

3

You need to use useRef hook:

const cciRef = useRef();

<CreditCardInput ref={cciRef}/>;
// cciRef.current holds the reference
export default function EditCard(props) {
  const cciRef = useRef();

  useEffect(() => {
    console.log(cciRef.current);
    cciRef.current.setValues({ number: "4242" });
  }, []);

  return (
    <View style={styles.container}>
      <CreditCardInput ref={cciRef} />
    </View>
  );
}
Sign up to request clarification or add additional context in comments.

2 Comments

Please update youyr answer to this, then I can mark it correct: This works: CCInput.current.setValues({{...})
Thanks for the answer, didn't realize its this simple with useRefs!

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.