Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable react-native AutoCorrect while text is inside TextInput?

I want autocorrect. However, when the user types "@", I want autoCorrect to turn off until otherwise.

I have tried setting the prop to false/true. However, the component does not change the setting (while there is text in the TextInput).

How can I get around this?

(iOS only)

like image 297
TIMEX Avatar asked May 04 '19 21:05

TIMEX


People also ask

How do I turn off autoCorrect in React Native?

To disable iOS keyboard suggestions in React Native, we can set the autoCorrect prop to false . to set autoCorrect to false . Now the keyboard suggestions should be hidden in iOS.

How do you Unfocus TextInput React Native?

To unfocus a TextInput in React Native, we can use the Keyboard. dismiss method. to set the onSubmitEditing prop to Keyboard. dismiss .


1 Answers

Demos

demo gifdemo2

Code

checkTest function

See code comments for the most important remarks.

checkText(text){
      //create a new regular expression 
      const regex = new RegExp("@");
      //check if the string contains an @ 
      const res = text.match(regex);

      // if res is not null, we have a match! 
      if (res != null){
        if (this.state.autoCorrect){
          // disable auto correction if it's still enabled
          this.input.blur(); 
          // hacky part, we need to dismiss the keyboard first, then we can show it again. 
          this.setState({autoCorrect: false}, () => {
            setTimeout(() => this.input.focus(), 60);
          });
        }
      }else{
        if (!this.state.autoCorrect){
          this.input.blur(); 
          // enable auto correction if no @ is detected anymore
          this.setState({autoCorrect: true}, () => {
            setTimeout(() => this.input.focus(), 60);
          });
        }
      }
      //update text in state 
      this.setState({ username: text});
    }

render function

 <View style={styles.container}>
     <TextInput 
      value={this.state.username}
      onChangeText={text => this.checkText(text)}
      autoCorrect={this.state.autoCorrect}
      />
 </View>

Complete Working Example

https://snack.expo.io/Skta6BJ34

Discussion

It seems, you need to "reload" the Keyboard to affect the reloading of the autoCorrect property. I think this is still a bug and is hopefully resolved in a future release. (see this github issue).

In the meanwhile, you can use this little workaround and maybe do some fine tuning on the timings/regex etc.

Edit:

I found an extensive answer here, this one tackles the issue similarly.

like image 199
Tim Avatar answered Oct 18 '22 02:10

Tim