Home > Mobile >  Ternary Operator React Native in StyleSheet
Ternary Operator React Native in StyleSheet

Time:10-25

Is there a way to use the Ternary Operator in the StyleSheet?

Currently, my TextInput looks as such:

.tsx

<TextInput
  defaultValue={selectedEvent ? selectedEvent.title : ""}
  style={[
    styles.textInput,
    { color: colorScheme === "dark" ? "#ffffff" : "#000000" },
  ]}
  onChangeText={inputChangeHandler}
/>

StyleSheet

const styles = StyleSheet.create({
  textInput: {
    borderBottomColor: "#ccc",
    borderBottomWidth: 1,
    marginBottom: 15,
    paddingVertical: 4,
    paddingHorizontal: 2,
  },
})

It'd be nice not to combine internal and external styles.

CodePudding user response:

Try this: In you TextInput:

style={styles.textInput(colorScheme)}

And in StyleSheet

textInput:(colorScheme)=> ({
  borderBottomColor: '#ccc',
  borderBottomWidth: 1,
  marginBottom: 15,
  paddingVertical: 4,
  paddingHorizontal: 2,
  color: colorScheme === "dark" ? "#ffffff" : "#000000"
}),

CodePudding user response:

The StyleSheet is generating static styling "classes", but you can define a light/dark class to use and append it to the array. It's not much different than what you've done already though.

Example:

<TextInput
  defaultValue={selectedEvent ? selectedEvent.title : ''}
  style={[
    styles.textInput,
    styles[colorScheme === 'dark' ? 'dark' : 'light'],
  ]}
  onChangeText={console.log}
/>

...

const styles = StyleSheet.create({
  ...
  textInput: {
    borderBottomColor: '#ccc',
    borderBottomWidth: 1,
    marginBottom: 15,
    paddingVertical: 4,
    paddingHorizontal: 2,
  },
  light: {
    color: '#000',
  },
  dark: {
    color: '#fff',
  },
});

Here's a running Expo Snack of the above code.

CodePudding user response:

In StyleSheet you can't use ternary. But what you can is combine ternary and stylesheet like that:

<div
    style={checkIfActive(props.position, 1)
        ? { ...styles.circle, ...styles.circleActive }
        : { ...styles.circle, ...styles.circleUnactive }}
/>

And you CSS can be:

circle: {
    width: '80%',
    margin: 'auto',
    height: 20,
    borderRadius: 10,
    borderStyle: 'solid',
    borderWidth: 1,
    borderColor: '#ffffff83',
},
circleUnactive: {
    backgroundColor: '#40c5ee4e',
},
circleActive: {
    backgroundColor: '#40c5ee',
},
  • Related