easyReact Native#4

TextInput controlled form

Prompt

Create a form with a TextInput for email and a submit Button. Validate that the email contains "@" before submitting. Show validation errors inline.

Solution

const [email, setEmail] = useState('')
const [error, setError] = useState('')
const handleSubmit = () => {
  if (!email.includes('@')) { setError('Invalid email'); return }
  setError(''); console.log('submit', email)
}
return (
  <View style={{ padding: 16, gap: 8 }}>
    <TextInput
      value={email}
      onChangeText={setEmail}
      placeholder="Email"
      style={{ borderWidth: 1, padding: 8, borderRadius: 4 }}
    />
    {error ? <Text style={{ color: 'red' }}>{error}</Text> : null}
    <Button title="Submit" onPress={handleSubmit} />
  </View>
)
Mentor's take

The controlled-input pattern makes React state the single source of truth: value={email} pins what the native field shows, onChangeText is the only way it changes. That single ownership is what makes validation, transformation (trimming, lowercasing), and programmatic resets trivial — the alternative is interrogating a ref and hoping the native view and your logic agree.

The validation timing is the senior detail. Validating on submit — not on every keystroke — is a UX decision: flashing "Invalid email" while the user is mid-typing "jo" punishes them for not being done. Errors are set at the submission boundary and cleared on the next successful submit, and they render inline next to the field rather than in an Alert, which would interrupt the flow and lose context.

Note the conditional render: {error ? <Text>...</Text> : null}. In React Native, accidentally rendering a bare string outside a <Text> (e.g. {error && ...} with a string) is a runtime crash, so the explicit ternary is the safe idiom.

Red flag: reading the field through a ref at submit time, or validating on every keystroke with an alert. Both say "I haven't built forms users had to live with."

Say it: "Controlled inputs make state the single source of truth; I validate at the submit boundary and render errors inline so the user is corrected without being interrupted."