Search code examples
javascriptreact-nativejsxrefactoring

React Native styling with conditional


I've recently started learning React Native. Currently, I'm working on altering the TextInput style when an error occurs.

How could I refine my code to make it look more polished?


<TextInput style={ (touched && invalid) ? {
    height: 40,
    backgroundColor: 'white',
    borderRadius: 5,
    padding: 10,
    borderWidth: 2,
    borderColor: 'red'
  } : {
    height: 40,
    backgroundColor: 'white',
    borderRadius: 5,
    padding: 10
  }
} />


Solution

  • 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.