Search code examples
react-nativeexporeact-native-textinput

React-Native: Adding text limit Indicator with a custom TextInput component


What I want to accomplish is a textInput that show a text like (0/255) in the side of itself.

The minimal code for the component:

    import React, { useState, useEffect} from 'react';
    import { View, TextInput, Text } from 'react-native';
    
    export default function InputWithIndicator({ Limit, ...otherProps }) {
      const [charRemains, setCharRemains] = useState(0);
      const [TextValues, setTextValues] = useState('');
      const [TextLimit] = useState(Limit);
    useEffect(() => {
          setCharRemains(Limit-TextValues.length);
    });
    
     return (
        <View >
          <TextInput {...otherProps} onChangeText={value=>setTextValues(value)}/>
          <Text>
            {charRemains}/{TextLimit}
          </Text>
        </View>
      );
    }

To place the component in code:

<InputWithIndicator placeholder="Your name" maxLength={25} Limit={25} onChangeText={value=>setName(value)} />

It works nice as component to display. But the major problem is the onChangeText does not return any value at all. Is there any way? FYI, I have tried with onChange Event, too.


Solution

  • Use onChange instead fo onChangeText

    Take a look at my sample: Sample