0
votes

I have rendered a flat list of multiple text inputs and an icon element in a react native component. What I'm trying to achieve is on click of any of the edit icon, I need to focus the correspondent text input. From the past experiences, I know using refs we can achieve this. However, how can I generate dynamic refs based on an index or any other value and focus to the correspondent text input?

const renderItem = ({ item,index }) => {
  return (
    <View style={styles.item} key={index}>
      <View style={styles.data}>
        <TextInput
          value={item.name}
          ref={(input) => {
            this.inputRef[item.name] = input;
          }}
        />
        <TouchableOpacity onPress={this.editName.bind(this, item.name,index)}>
        <Icon
          name="pencil"
          size={20}
        />
        </TouchableOpacity>
      </View>
    </View>
  )
}

Function to focus to input:

editName = (name,index) => {
  this.inputRef[name].focus();
}

Error: Can't set property 'someName' of undefined. The app is crashing even before the onClick event happens.

Thanks!

1

1 Answers

0
votes

I wouldn't get mixed with the bind function.

If you identify your inputs by their name, stick with this when you apply the editName function as well:

function App() {
  const names = ['1', '2', '3'];
  const inputRef = useRef([]);

  // Note this returns a function, that uses the relevant `name` value
  const editName = (name) => () => inputRef.current[name].focus();

  return (
    <div className="App">
      {names.map((name) => (
        <div key={name}>
          <input
            type="text"
            ref={(input) => {
              inputRef.current[name] = input;
            }}
          />
          <button onClick={editName(name)}>{`Edit ${name}`}</button>
        </div>
      ))}
    </div>
  );
}

You can check it online as well