How to add styling with conditional with React Native?

Sometimes, we want to add styling with conditional with React Native.

In this article, we’ll look at how to add styling with conditional with React Native.

How to add styling with conditional with React Native?

To add styling with conditional with React Native, we can use a function.

For instance, we write:

import * as React from 'react';
import { TextInput, View } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

export default function App() {
  const [val, setVal] = React.useState();
  const getStyles = () => {
    return {
      border: !val ? '1px solid red' : 'none',
    };
  };

  return (
    <View>
      <TextInput
        value={val}
        onChangeText={setVal}
        style={getStyles()}
        placeholder="name"
      />
    </View>
  );
}

to define the getStyles function that returns an object with the border style according to the value of val.

We use the object getStyles return as the value of style.

And we call setVal when we type into the text input.

Therefore, when the input is empty, we see a red border and no border otherwise.

Conclusion

To add styling with conditional with React Native, we can use a function.