Search code examples
javascriptreactjsreact-nativejsxconditional-rendering

How to do conditional rendering in react native


How to do conditional rendering in react native with more than 1 condition?

Following is some portion of my code

Index

 .then(response => response.json())
          .then((responseData) => {
             this.setState({
           progressData:responseData,
          });
    .....
    ......
      render() {

        const { progressData }= this.state;
      return(
        <View style={{flex:1}}>
        <HeaderExample />
        <View>
         {progressData == "1"} 
               (<View>

                 <Text style={{fontSize:28,color:"#8470ff",fontWeight: 'bold',paddingTop:20,alignSelf:'center'}}>Pending</Text>

                </View>)}
{  progressData == "2" && 
           (<View>
             <CardSection>
             <Text style={{fontSize:28,color:"#8470ff",fontWeight: 'bold',paddingTop:20,alignSelf:'center'}}>InProgress </Text>

             <View style={styles.buttonContainer}>
             <Button
             title="Report"
             color="#8470ff"
             onPress={() =>onPressReport()}
             />

             </View>)}

But here it is for a single case means if responseData contains only one field. But now the reponseData contains 2 arrays. Each with 3 objects. So how do I check conditional rendering here?My responseData looks like this. I want to populate some UI on each condition. That means if status = 1 && work_type ="plumber" then render some UI. Also if status = 2 && work_type="electrical" && assigend_to="worker_45" then render some ui. So how do I do this?

Please help


Solution

  • You can move your render in a new variable, or function. to keep clear the render function

     render() {
    
            const { progressData }= this.state;
          return(
            <View style={{flex:1}}>
            <HeaderExample />
            <View>
            {renderProgressData(progressData)}
            ... //rest of your code
          )
      }
    

    and in your renderProgressData function you can create a switch

    renderProgressData = (progress) => {
       switch(progress) {
        case 1:
            return (<View>1</View>)
        case 2:
             return (<View>1</View>)
        // ...  and so on
        default:
            return (<View>Default View</View>)
       }
    }
    

    It is a little cleaner in this way for me.