3

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?

EDIT: I've cut the component right down to this:

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

const TextBox = () => {
  console.log('Rendering');
  return <TextInput />;
};

export default TextBox;

Even this loses focus each time I enter a character. However, I only see the 'Rendering' log once. I've also tried importing TextInput from react-native rather than react-native-paper, but that didn't make any difference.

Sharon
  • 3,471
  • 13
  • 60
  • 93

2 Answers2

2

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;
RamaProg
  • 1,106
  • 7
  • 15
1

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.

Adem79
  • 11
  • 4