Changing Style as State Changes in React Native

Sometimes you want to change the look of the UI when an event happens. For example, when you are validating user input and a user does not enter anything into a text box you may want to change the color of the border from black to red as a sign to the user that they need to enter something.

In React Native, a component is drawn based on the current state. That means the component needs to be configured to be drawn based on whatever possible states could occur.

The style property of a component can be configured to accept multiple styles.

style={[styles.base, styles.background]}

The styles are applied from left to right. If a style appears multiple times, the right most style takes precedence.

Styles can also be added conditionally.

style={[styles.base, && styles.background]}

In this case the background style will only be applied if the state value active is true. This can be used in validating a form. The base style sets the normal appearance of a TextInput component for example. During validation if an error occurs, a state value could be set which would cause the right most style to be applied. If no error occurred then the state value would be set so the right most style would not be applied.

Here is an example of toggling a style based on a state value.

We will create a state value called toggle and initialize it to false.

getInitialState: function () {
    return { toggle: false };

We will setup a TextInput and a TouchableHighlight component to give us a text box and button.

The TextInput uses textInput as it’s base style and if this.state.toggle is true, the textInputAlt style is also applied.

    style={[styles.textInput, this.state.toggle && styles.textInputAlt]}  

The onPress event of TouchableHighlight toggles this.state.toggle back and forth between true and false.

    onPress={()=> this.setState({toggle: !this.state.toggle})}
    <Text style={styles.buttonText}>

The textInput style centers the TextInput component and makes the border black.

textInput: {
    borderColor: '#000',
    borderWidth: 2.0,
    backgroundColor: '#fff',
    height: 40,
    marginLeft: 60,
    marginRight: 60,
    marginBottom: 30,
    padding: 2,

The textInputAlt style changes the border to a reddish color.

textInputAlt: {
    borderColor: '#e71636',

The initial screen shows a black border.

When the Go button is tapped, the border changes to red.

Below is the entire code.