React Native Set TextInput Value Uppercase

Viewed 9256

I'm new in React Native and not sure why it shows unexpected result. If I type 'a' then 'a' it shows 'AAA', and so on.

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      userName: ''
    }
  }

  formatUserName = (textValue) => {
    // If I remove toUpperCase() below, it shows expected result.
    this.setState({ userName: textValue.toUpperCase() });
  }

  render() {
    ...
    <TextInput
      onChangeText={textValue => this.formatUserName(textValue)}
      value={this.state.userName} />
    ...
  }
}
2 Answers

If you want to change input string to uppercase string, then you can use autoCapitalize props in TextInput.

<TextInput
  autoCapitalize = {"characters"}
  onChangeText={(text) => this.setState({ userName: text })}
  value={this.state.userName} />

Props autoCapitalize has following options:

  • characters: all characters.
  • words: first letter of each word.
  • sentences: first letter of each sentence (default).
  • none: don't auto capitalize anything.

Default value is sentences

I also had the same problem. In iOS it works perfectly but there's a problem only in android.

This one small hack seemed to work for me:

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      userName: ''
    }
  }

  formatUserName = (textValue) => {
    this.setState({ userName: textValue.toUpperCase() });
  }

  render() {
    ...
    <TextInput
      onChangeText={textValue => this.formatUserName(textValue)}
      keyboardType={Platform.OS === 'ios' ? 'default' : 'visible-password'}
      value={this.state.userName} />
    ...
  }
}
Related