Home > Net >  My React Native Text Input is losing focus after each character is entered
My React Native Text Input is losing focus after each character is entered

Time:04-21

I have a TextBox Component which renders an Input box in my React Native app. It uses react-native-paper:

import * as React from 'react';
import {View} from 'react-native';
import {TextInput} from 'react-native-paper';

const TextBox = () => {
  const [text, setText] = React.useState('');
  return (
    <View>
      <TextInput value={text} onChangeText={e => setText(e)} />
    </View>
  );
};

export default TextBox;

This basically replicates what's in the RN Paper docs, but the Text Input doesn't work. It renders ok, but as soon as I enter anything in the box, that character is rendered but the focus is shifted away from the box, so I have to tap on it again to type the next character.

I've seen quite a few people with a similar issue, but none of the suggested fixes have worked - they mainly seem to be saying that the component needs to be separated out into its own function, but I think that's what I've done here, isn't it?

I've tried things like setting the value to be fixed (eg value='Test') but it still loses focus as soon as I try to type.

Can anyone see what I'm doing wrong here?

CodePudding user response:

if i'm not mistaken:

When your onChangeText event fires, the callback calls setState with the new title value, which gets passed to your text input as a prop. At that point, React renders a new component, which is why you lose focus.

try to provide a constant key for the components and precisely the TextBox components.

CodePudding user response:

Try this:

import React, { useState } from 'react';
import { TextInput } from 'react-native-paper';

const TextBox = () => {
  const [text, onChangeText] = useState('');

  return <TextInput value={text} onChangeText={onChangeText} />;
};

export default TextBox;
  • Related