Search code examples
javascriptreact-nativetexttextinput

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)


Solution

  • 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.