0

I'm trying to show an alert when the user's input reaches six to twelve characters. I see that it only shows an alert if the character reaches 7.

Live editing here: https://snack.expo.dev/@vicrn101/66bbfe

Here's my code:

import React, {useEffect, useState} from "react";
import { Text, TextInput, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

export default function App() {
const [moreThanSix, setMoreThanSix] = useState(false);

const validateEntry = (textEntry) => {
console.log('textEntry: ', textEntry);
console.log('length: ', textEntry.length);

if(textEntry.length > 5 && textEntry.length < 13) {
    console.log('moreThanSix: ', textEntry.length);
    setMoreThanSix(true);
} else {
    setMoreThanSix(false)
}

console.log('moreThanSix: ', moreThanSix);
if(moreThanSix) {
  alert('SixToTwelveCharacters: ', moreThanSix);
}
}

return (
<View style={styles.container}>
  <Text style={styles.paragraph}>
    Show alert when text length is 6 to 12 characters.
  </Text>
  <Card>
    <Text>Is six to twelve characters: {moreThanSix}</Text>

    <TextInput
      onChangeText={(textEntry) => validateEntry(textEntry)}
    />
  </Card>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
 },
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
 },
 });

Live editing here: https://snack.expo.dev/@vicrn101/66bbfe

Vic Andam
  • 823
  • 2
  • 7
  • 17
  • You do not need a state to this. This will be better for performance and you will not have this issue. Change your `validateEntry` function to ` if(textEntry.length > 5 && textEntry.length < 13) { alert('More or equal than 6 and less or equal than 12'); }` – David Scholz Aug 31 '22 at 09:00
  • I need a state here because that moreThanSix variable is being used in views that conditionally render if that condition is met and as you can see it is a boolean variable that I used to conditionally render some text if it is true. @DavidScholz – Vic Andam Aug 31 '22 at 09:05
  • 1
    The problem with your code is that you are setting the value of state `moreThanSix` and immediately on the next line you are expecting an updated state, react does not work like this, you will receive the updated state inside the function on the next render, so for your solution, check the length according to @DavidScholz 's comment, and set the state value as well for your rendering UI purposes. – Shashank Mishra Aug 31 '22 at 09:17

0 Answers0