4

I have a React Native textInput and a button and I would like to remove the focus from the textInput if I were to click on the button. Would that be possible?

My TextInput looks like this:

        <TextInput
            onChangeText={onChange}
            value={searchQuery}
            placeholder="Start typing to search or add your own"
            maxLength={80}
            onFocus={() => {
                setIsInputFocused(true);
            }}
            onBlur={() => {
                setIsInputFocused(false);
                setSearchQuery('');
            }}
            blurOnSubmit={true}
        />

And then I have a pressable element:

<View onPress={() => { //remove focus from Text Input }></View>

1 Answer 1

3

The useImperativeHandle hook is the one you need here, And forwardRef, useRef hooks. I have created a new TextInput called ControlledTextInput to pass a react ref to it and expose the blur method outside (App component level). Note that there are two refs one is coming as a prop(to which we bind the functions) and the one inside ControlledTextInput(which is the ref to the actual text input)

import React, { useImperativeHandle, forwardRef, useRef } from "react";
import { StyleSheet, Text, View, TextInput, Button } from "react-native";

const ControlledTextInput = forwardRef((props, ref) => {
  const internalInputRef = useRef();
  useImperativeHandle(ref, () => ({
    blur: () => {
      internalInputRef.current.blur();
    }
  }));

  return (
    <TextInput
      placeholder={"Type something"}
      style={styles.textInputStyle}
      ref={internalInputRef}
    />
  );
});

const App = () => {
  const inputRef = useRef(null);

  return (
    <View style={styles.app}>
      <View style={styles.header}>
        <Text style={styles.title}>Focus lose when button click</Text>
      </View>
      <ControlledTextInput ref={inputRef} />
      <Button title="Click ME" onPress={() => inputRef.current.blur()} />
    </View>
  );
};

const styles = StyleSheet.create({
  app: {
    marginHorizontal: "auto",
    maxWidth: 500
  },
  header: {
    padding: 20
  },
  title: {
    fontWeight: "bold",
    fontSize: "1.5rem",
    marginVertical: "1em",
    textAlign: "center"
  },
  textInputStyle: {
    border: "2px solid black",
    maxWidth: 500,
    height: 50,
    textAlign: "center",
    fontSize: 20
  }
});

export default App;

React Native Codesandox:

Edit remove focus from a React Native TextInput on button click

Sign up to request clarification or add additional context in comments.

1 Comment

@Bobimaru, check this out!!

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.