0

i cant seem to get my head around this. I want to to use a button to use .focus() on my textinput in react native. How do i pass the ref to my function and call that method?

const [{ingredients}, dispatch] = React.useContext(AddRecipeContext);
const [edit, setEdit] = React.useState('');

const startEdit = (key: string, ref: any) => {
       ref.current.focus();
       setEdit((prev) => (prev === key? '':key)) 
    }
const _renderItem = ({ item  }: {item: IIngredient}) => {
   var textInputRef: any = React.createRef();
   return (
      <View key={item.key}>
         <TextInput 
          ref={textInputRef} 
          onChangeText={label => setIngredientLabel(item.key, label) }
          value={item.label.toString()}/>
         <Pressable onPress={() => startEdit(item.key, textInputRef)}/>
      </View>
   );
};

const RenderIngredients = ingredients.map((item: IIngredient) => _renderItem({item}));

return (
  <View>
     <ScrollView> 
        {RenderIngredients}
     </ScrollView>
  </View>
);

What is the correct way to handle refs?

Thank you in advance.

EDIT: ref.focus(); to ref.current.focus();

zebra
  • 23
  • 4

2 Answers2

0

This should do the job

const [{ ingredients }, dispatch] = React.useContext(AddRecipeContext);
const [edit, setEdit] = React.useState("");

const _renderItem = ({ item }: { item: IIngredient }) => {
  var textInputRef: any = React.createRef();

  return (
    <View key={item.key}>
      <TextInput
        ref={textInputRef}
        onChangeText={(label) => setIngredientLabel(item.key, label)}
        value={item.label.toString()}
      />

      <Pressable
        onPress={() => {
          textInputRef.current.focus(); 
          // current was missing
          setEdit((prev) => (prev === item.key ? "" : item.key));
        }}
      />
    </View>
  );
};

const RenderIngredients = ingredients.map((item: IIngredient) =>
  _renderItem({ item })
);

return (
  <View>
    <ScrollView>{RenderIngredients}</ScrollView>
  </View>
);
Kartikey
  • 4,516
  • 4
  • 15
  • 40
  • That didnt work for me. It says: TypeError: null is not an object (evaluating 'textInputRef.current.focus') – zebra Apr 20 '21 at 09:01
0

Your forgot the current object with the ref: ref.focus(); should be ref.current.focus();

See how to accessing refs

Chris
  • 124
  • 1
  • 5
  • That didnt work for me. It says: TypeError: null is not an object (evaluating 'textInputRef.current.focus') I'll update the question though, thank you – zebra Apr 20 '21 at 09:26
  • Yes this is because at initialization the ref is set to `null`. To avoid this, you should add some conditions like `textInputRef?.current?.focus()`. This is equal to `if (textInputRef && textInputRef.current) { textInputRef.current.focus() }` – Chris Apr 20 '21 at 09:47