0

How do you render a textInput conditionally such that when the value text in the textInput characters is less than 6, it logs an error when the user clicks the ok button

const [text, setText] = useState('')
<TextInput
  style={styles.textInputStyle}
  value={text}
  onChangeText = {(text) => setText(text)}
  placeholder="Text"
  placeholderTextColor="#60605e" />
<TouchableOpacity style={styles.button}
  onPress={() => {setText(text)} }>
  <Text style={styles.buttonTitle}>OK</Text>
</TouchableOpacity>
3
  • What is pricealert? Commented Oct 12, 2020 at 18:15
  • Please make a working code example for your question, generally speaking you render conditionally by let's say smth like this {myBool && <div>smth</div>} Commented Oct 12, 2020 at 18:16
  • You don't need conditional rendering for this, your onPress handler needs to check the text length and log the error if text.length < 6. Commented Oct 12, 2020 at 18:50

1 Answer 1

2

Your onPress callback can manage this. It needs to do a check for text.length < 6 and then branch based off of the result. It might look like this (I removed the styling logic to showcase the callback):

const MyComponent = () => {
  const [text, setText] = useState('');

  return (
    <>
      <TextInput
         value={text}
         onChangeText = {(text) => setText(text)}
      />
      <TouchableOpacity
        onPress={() => {
          if(text.length < 6) {
            // Alert user of invalid input
            Alert.alert("Input must be less than 6 characters!") ;
            return;
          }
          // ... continue on to the desired task
        }}
      >
        <Text>OK</Text>
      </TouchableOpacity>
    </>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.