React Native styling with conditional

Viewed 102866

I'm new to react native. I'm trying to change the styling of the TextInput when there is an error.

How can I make my code not as ugly?

<TextInput
      style={touched && invalid?
        {height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10, borderWidth: 2, borderColor: 'red'} :
        {height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10}}
</TextInput>
3 Answers

There are two ways, by inline or calling a function:

1)

const styles = StyleSheet.create({
    green: {
        borderColor: 'green',
    },
    red: {
        borderColor: 'red',
    },
    
});

<TextInput style={[styles.otpBox, this.state.stateName ?
    styles.green :
    styles.red ]} />
getstyle(val) {
    if (val) {
        return { borderColor: 'red' };
    }
    else {
        return { borderColor: 'green' };
    }
}

<TextInput style={[styles.otpBox, this.getstyle(this.state.showValidatePOtp)]} />
Related