Search code examples
apireact-nativeconditional-statementsstyling

React Native conditional styling based on text returned by an API call


I am trying to apply conditional styling to text elements. The text values are extracted from a live API.

I have a train live status app that returns “Good Service”, “Minor Delays” and so on for each line. I would like to change the styling of the text based on the value. If it says “Good Service”, I will keep the text normal. If it says anything else, I would like to change it to red font.

Please see my Expo Snack prototype. https://snack.expo.io/@leourushi/api+conditional-styling

This is where I'm extracting the information for each train line from a live API. I'm using axios method to get all the lines ready before displaying them.

  async componentDidMount(){
    var request_1 = 'https://api.tfl.gov.uk/Line/bakerloo/Status';
    var request_2 = 'https://api.tfl.gov.uk/Line/central/Status';
    var request_3 = 'https://api.tfl.gov.uk/Line/circle/Status';
    var request_4 = 'https://api.tfl.gov.uk/Line/district/Status';
    var request_5 = 'https://api.tfl.gov.uk/Line/hammersmith-city/Status';


  const [func1, func2, func3, func4] = await Promise.all([
    axios.get(request_1),
    axios.get(request_2),
    axios.get(request_3),
    axios.get(request_4)
  ]);

  const func5 = await axios.get(request_5);

  this.setState({
    dataSource: func1.data[0].lineStatuses,
    dataSource2: func2.data[0].lineStatuses,
    dataSource3: func3.data[0].lineStatuses,
    dataSource4: func4.data[0].lineStatuses,
    dataSource5: func5.data[0].lineStatuses,

    isLoading: false
  });

And I display the extracted strings here:

        <FlatList
          style={styles.rightColumn}
          data={this.state.dataSource}
          renderItem={({item}) => <Text style={styles.rightColumnText}>{item.statusSeverityDescription} </Text>}
          keyExtractor={({id}, index) => id.toString()}
        />

The result typically says "Good Service", "Minor Delays" or other short phrases.

I want to change the styling of the text (styles.rightColumn) depending on the result returned by the API call. Is there a way to change styling so that it will behave as below?

If it returns "Good Service" = plain black font.

If it returns anything else = red font.


Solution

  • You can easily achieve this behavior by modifying your renderItem function as follows:

    renderItem={({item}) => <Text style={[styles.rightColumnText, {color:  item.statusSeverityDescription == "Good Service" ? 'black' : 'red'}]}>{item.statusSeverityDescription} </Text> }
    

    Explanation:

    Here we are overriding our standard color depending on the value of item.statusSeverityDescription. If the status is not equal to "Good Service", we change the font color to red. BTW in this example we make use of the ternary operator.

    style={[styles.rightColumnText, {color:  item.statusSeverityDescription == "Good Service" ? 'black' : 'red'}]}