0
votes

I am still having trouble understanding ref's in React Native (and React in general). I am using functional component. I have a FlatList that has many items. How do I create a reference for a thing within an item like a Text or View component?

<FlatList
 data={data}
 renderItem={({ item }} => {
   <View>

    ... lots of other stuff here

    <TouchableOpacity onPress={() => _editITem(item.id)}>
      <Text ref={(a) => 'text' + item.id = a}>EDIT</Text>
    </TouchableOpacity>

  </View>
 }
/>

Then in _editItem I want to reference the Text component so that I can change its text from 'EDIT' to 'EDITING', or even change its style, or whatever.

_editPost = id => {
  console.log(text + id)
}

I have tried...

FeedComponent = () => {
  let editPosts = {}

 <FlatList
 data={data}
 renderItem={({ item }} => {
   <View>

    ... lots of other stuff here

    <TouchableOpacity onPress={() => _editITem(item.id)}>
      <Text ref={(a) => editPosts[item.id] = a}>EDIT</Text>
    </TouchableOpacity>

  </View>
 }
/>

...and a few other things, but I think I might be way off so I could use some guidance.

1

1 Answers

1
votes

Typically you don't use refs in react to update content like text. Content should be rendered based on the current props and state of your component.

In the case you describe you'll probably want to set some state in the parent component that then impacts the rendering of the item.

As a sidenote refs are used if you need to trigger a method on a child component like calling focus on a TextInput for example but not for imperatively updating component content.

In your case you'll want to update some state representing the current active item. Something like:

import React, {useState} from 'react';
FeedComponent = () => {
  const [activeItem, setActiveItem] = useState(null);

 <FlatList
 data={data}
 renderItem={({ item }} => {
   return (
   <View>

    ... lots of other stuff here

    <TouchableOpacity onPress={() => setActiveItem(item.id)}>
      {activeItem === item.id
          ? <Text>EDITING</Text>
          : <Text>EDIT</Text>
      }
    </TouchableOpacity>

  </View>
 );
 }
 extraData={activeItem}
/>