4

I have a TextInput component, which is only editable on component mount. It should become editable and auto focused, when a button is pressed. As I understood it correctly, the autoFocus property only works on first mount. Is there any way to implement this on state change?

import { FunctionComponent } from 'react';
import { View, TextInput, TextInputProps } from 'react-native';


interface InputTextBoxProps {
  editingState: boolean;
}

type InputProps = TextInputProps & InputTextBoxProps;

const InputTextBox: FunctionComponent<InputProps> = ({editingState, ...props}) => {
  return (
    <View>
      <TextInput
        {...props}
        multiline={true} 
        style={styles.textStyle}
        editable={editingState}
        autoFocus={editingState}
      >
      </TextInput>
    </View>
  );
};
1

3 Answers 3

13
const refInput = React.useRef(null);
 ...
<TextInput
  {...props}
  ref={refInput}
  multiline={true} 
  style={styles.textStyle}
  editable={editingState}>
</TextInput>

on button click function

refInput.current.focus()
Sign up to request clarification or add additional context in comments.

Comments

2

Update

Here's the working solution, as the editable prop seems to work only on component mount, so it won't change via state. This solution is built on mainak's answer.

import { FunctionComponent, useRef } from 'react';
import { View, StyleSheet, TextInput, TextInputProps } from 'react-native';

interface InputTextBoxProps {
  editingState: boolean;
}

type InputProps = TextInputProps & InputTextBoxProps;

const InputTextBox: FunctionComponent<InputProps> = ({editingState, ...props}) => {

  const refInput = useRef<TextInput>(null);

  if (editingState) {
    refInput.current?.focus();
  } else {
    refInput.current?.blur();
  }

  return (
    <View pointerEvents={editingState ? 'auto' : 'none'}>
      <TextInput
        {...props}
        ref={refInput}
        multiline={true}
      >
      </TextInput>
    </View>
  );
};

Comments

0

You can use autoFocus which works fine for me

const [focusedInput, setFocusedInput] = useState(false);

<TextInput
     placeholder="Search Manifest ID"
     style={styles.SearchInput}
     placeholderTextColor={'#808080'}
     value={search}
     onChangeText={setSearch}
     onSubmitEditing={() => { onSubmitted(); }}
    autoFocus={focusedInput} // here its working for me
/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.