Anders Pedersen
Anders Pedersen

Reputation: 2385

React native - Highlight a TextInput if it's empty on form submit

I have a bunch of TextInput fields, and on form submit i would like to highlight the ones that are left empty or with invalid content. (using a border)

Whats is a good approach for handling this with minimum code ?

having a state for "isEmpty" which is being updated on submit and conditionally render the css for each of them seems a bit overkill since there is quite a few fields.

Is there a way to fetch a TextInput by an ID or name and dynamically update or append to the CSS rules that way in React Native

Upvotes: 3

Views: 11530

Answers (3)

Roc Khalil
Roc Khalil

Reputation: 1385

Personal suggestion:

1- add a state errors: []

2- on submit, check for the required values an fill the errors with custom data; example:

onSubmit() {
  let errors = []
  let { firstName, lastName } = this.state

  if (firstName === ''){
    errors.push('firstName')
  }

  if (lastName === ''){
    errors.push('lastName')
  }

  if (errors.length) { 
    this.setState({ errors });
    return;
  }

  // API CALL
}

3- in your render function, add a custom class for your TextInputs

render(){
  return (
    <TextInput style={{ borderColor: this.state.errors.include('firstName') ? 'red' : 'transparent' }} />
  )
}

Now of course, I would suggest to move the styles to classes and use the classes, but this example is a head start for a way to implement them.


EDIT

I forgot to mention that you need to setState({ errors: [] }) when you edit any value in your textbox to reset the borders to null.

Upvotes: 7

Raymond Mutyaba
Raymond Mutyaba

Reputation: 950

You can use stylesheets to define styles. Then modify the styles depending on the value of the input.

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

class YourComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
        };
    }

    isInvalid = (input) => {
      'Check if input is empty or invalid and return true if it is and false if it is not.'
    }

    handleUsernameInput = (input) => {
        this.setState({username:text});
        if(this.isInvalid(input)) {
            styles.usernameInput.borderColor = '#990000';
            styles.usernameInput.borderWidth = 1;
        } else {
            if(styles.usernameInput.borderColor) {
                delete styles.usernameInput.borderColor;
                delete styles.usernameInput.borderWidth;
            }
        }
    }

    render() {
        return(
            <View style={styles.container}>
                <TextInput style={styles.usernameInput} onChangeText={(event) => this.handleUsernameInput(event)} value={this.state.username}/>
            </View>
        );
    }
}

export default YourComponent;

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    usernameInput: {
        fontSize: 16,
        padding: 15,
    },
});

Upvotes: 0

Ravi.K
Ravi.K

Reputation: 41

You can do this by using React-Native Direct Manipulation

onSubmit(){
   const {firstName, lastName} = this.state;
   if(firstName.trim().length == 0){
      this.firstNameInput.setNativeProps({
        borderColor:'red',
        borderWidth:1
      });
      return;
   }

   if(lastName.trim().length == 0){
      this.lastNameInput.setNativeProps({
        borderColor:'red',
        borderWidth:1
      });
      return;
   }
}

And you textInput will look like

<TextInput ref={r=>this.firstNameInput=r} onChangeText={(firstName)=>this.setState({firstName})} />
<TextInput ref={r=>this.lastNameInput=r} onChangeText={(lastName)=>this.setState({lastName})} />

Upvotes: 1

Related Questions