React Native styling with conditional

React Native

React Native Problem Overview


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>

React Native Solutions


Solution 1 - React Native

Use StyleSheet.create to do style composition like this,

make styles for text, valid text, and invalid text.

const styles = StyleSheet.create({
    text: {
		height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10, 
	},
	textvalid: {
		borderWidth: 2,
	},
    textinvalid: {
    	borderColor: 'red',
    },
});

and then group them together with an array of styles.

<TextInput
	style={[styles.text, touched && invalid ? styles.textinvalid : styles.textvalid]}
</TextInput>

For array styles, the latter ones will merge into the former one, with overwrite rule for the same keys.

Solution 2 - React Native

Update your code as following:

<TextInput style={getTextStyle(this.state.touched, this.state.invalid)}></TextInput>

Then outside your class component, write:

getTextStyle(touched, invalid) {
 if(touched && invalid) {
  return {
    height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10, borderWidth: 2, borderColor: 'red'
  }
 } else {
   return {
      height: 40, backgroundColor: 'white', borderRadius: 5, padding: 10
   }
 }
}

Solution 3 - React Native

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

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

<TextInput style={[styles.otpBox, this.state.stateName ?    styles.green :    styles.red ]} />

2)

getstyle(val) {
    if (val) {
        return { borderColor: 'red' };
    }
    else {
        return { borderColor: 'green' };
    }
}

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKelvinView Question on Stackoverflow
Solution 1 - React NativeValView Answer on Stackoverflow
Solution 2 - React NativeRohan KangaleView Answer on Stackoverflow
Solution 3 - React NativePravin GhorleView Answer on Stackoverflow