Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native styling with conditional

Tags:

react-native

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> 
like image 352
Kelvin Avatar asked Aug 03 '17 08:08

Kelvin


People also ask

How do you apply style based on condition in react native?

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', }, });

How do you apply conditional styling?

Conditional Styling with Inline Styles Add the following code to your App. js: import { React, useState } from "react"; import "./App. css" function App() { const styles = { popup:{ display:"none", opacity:"0" } }; return ( <div className="main"> <button className="open_button">Open!

How do you use multiple styles in react native?

react-native Styling Adding multiple styles You can pass an array to the style prop to apply multiple styles. When there is a conflict, the last one in the list takes precedence.

What is conditional styling?

What Is Conditional Styling? In simple words, it is changing CSS based on a set of conditions or a state. The CSS that will be changed and/or added based on a condition can be inline styles or styled components among the many different ways of adding CSS in React.


2 Answers

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.

like image 129
Val Avatar answered Sep 21 '22 07:09

Val


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    }  } } 
like image 42
Rohan Kangale Avatar answered Sep 20 '22 07:09

Rohan Kangale