How to Limit Maximum Number of Characters in React Native TextInput

Sometimes you don’t want the user to input many characters through React Native TextInput component. Fortunately, react native TextInput has a prop to limit the characters the user enters.

The maxLength property of TextInput limits the number of maximum characters that can be entered. You can use it as given in the code snippet given below:

import React from 'react';
import {StyleSheet, TextInput, View} from 'react-native';

const App = () => {
  const [text, onChangeText] = React.useState('');
  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        maxLength={8}
        onChangeText={onChangeText}
        value={text}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  input: {
    height: 40,
    width: '80%',
    margin: 12,
    borderWidth: 1,
    padding: 10,
  },
});

export default App;

As you see, the maximum number of characters that can be entered is limited to 8 in the example given above.

Have any doubts? Take a look at the official React Native document here.

Similar Posts

Leave a Reply