1

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

3
  • 1
    Try condition ? <MyComponent /> : null instead of condition && <MyComponent /> Commented Oct 31, 2018 at 11:46
  • So how do I map over each element here? Commented Oct 31, 2018 at 11:49
  • Why you want to map? How exactly ? Commented Oct 31, 2018 at 11:53

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.