Ad

Accessing Refs In React Functional Component

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>
  );
}
Ad

Answer

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>
  );
}
Ad
source: stackoverflow.com
Ad