[javascript] if-else statement inside jsx: ReactJS

I need to change render function and run some sub render function when a specific state given,

For example:

render() {
    return (   
        <View style={styles.container}>
            if (this.state == 'news'){
                return (
                    <Text>data</Text>
                )
            }
        </View>
    )
}

How can I implement that without changing scenes, I will use tabs to change content dynamically.

This question is related to javascript reactjs react-native

The answer is


You can achieve what you are saying by using Immediately Invoked Function Expression (IIFE)

render() {
    return (   
        <View style={styles.container}>
            {(() => {
              if (this.state == 'news'){
                  return (
                      <Text>data</Text>
                  )
              }
              
              return null;
            })()}
        </View>
    )
}

Here is the working example:

Edit awesome-yalow-eb2nu

But, In your case, you can stick with the ternary operator


What about switch case instead of if-else

  render() {
    switch (this.state.route) {
      case 'loginRoute':
        return (
            <Login changeRoute={this.changeRoute}
              changeName={this.changeName}
              changeRole={this.changeRole} />
        );
      case 'adminRoute':
        return (
            <DashboardAdmin
              role={this.state.role}
              name={this.state.name}
              changeRoute={this.changeRoute}
            />
        );
      default: 
        return <></>;
    }

For this we can use ternary operator or if there is only one condition then "&&" operator .Like this:-

//This is for if else

render() {

return (   
    <View style={styles.container}>
      {this.state == 'news') ?
           <Text>data</Text>
        : null}
    </View>
)

}

//This is only for if or only for one condition

render() {

return (   
    <View style={styles.container}>
      {this.state == 'news') &&
           <Text>data</Text>
        }
    </View>
)

}


I find this way is the nicest:

{this.state.yourVariable === 'news' && <Text>{data}<Text/>}

You can do this. Just don't forget to put "return" before your JSX component.

Example:

render() {
    if(this.state.page === 'news') {
        return <Text>This is news page</Text>;
    } else {
        return <Text>This is another page</Text>;
    }
}

Example to fetch data from internet:

import React, { Component } from 'react';
import {
    View,
    Text
} from 'react-native';

export default class Test extends Component {
    constructor(props) {
        super(props);

        this.state = {
            bodyText: ''
        }
    }

    fetchData() {
        fetch('https://example.com').then((resp) => {
            this.setState({
                bodyText: resp._bodyText
            });
        });
    }

    componentDidMount() {
        this.fetchData();
    }

    render() {
        return <View style={{ flex: 1 }}>
            <Text>{this.state.bodyText}</Text>
        </View>
    }
}

You can't provide if-else condition in the return block, make use of ternary block, also this.state will be an object, you shouldn't be comparing it with a value, see which state value you want to check, also return returns only one element, make sure to wrap them in a View

render() {
    return (
      <View style={styles.container}>
      {this.state.page === 'news'? <Text>data</Text>: null}
      </View>

     )
}

                        <Card style={{ backgroundColor: '#ffffff', height: 150, width: 250, paddingTop: 10 }}>
                            
                            <Text style={styles.title}>     {item.lastName}, {item.firstName} ({item.title})</Text> 
                            <Text >     Email: {item.email}</Text>
                            {item.lastLoginTime != null ? <Text >     Last Login: {item.lastLoginTime}</Text> : <Text >     Last Login: None</Text>}
                            {item.lastLoginTime != null ? <Text >     Status: Active</Text> : <Text >     Status: Inactive</Text>}
                           
                        </Card>

 render() {
     return (   
         <View style={styles.container}>
         (() => {                                                       
             if (this.state == 'news') {
                return  <Text>data</Text>
            }
            else 
             return  <Text></Text>
        })()
         </View>
     )
 }

https://react-cn.github.io/react/tips/if-else-in-JSX.html


There's a Babel plugin that allows you to write conditional statements inside JSX without needing to escape them with JavaScript or write a wrapper class. It's called JSX Control Statements:

<View style={styles.container}>
  <If condition={ this.state == 'news' }>
    <Text>data</Text>
  </If>
</View>

It takes a bit of setting up depending on your Babel configuration, but you don't have to import anything and it has all the advantages of conditional rendering without leaving JSX which leaves your code looking very clean.


Simple example of nested loop with if condition in React:

Data example:

    menus: [
    {id:1, name:"parent1", pid: 0},
    {id:2, name:"parent2", pid: 0},
    {id:3, name:"parent3", pid: 0},
    {id:4, name:"parent4", pid: 0},
    {id:5, name:"parent5", pid: 0},
    {id:6, name:"child of parent 1", pid: 1},
    {id:7, name:"child of parent 2", pid: 2},
    {id:8, name:"child of parent 2", pid: 2},
    {id:9, name:"child of parent 1", pid: 1},
    {id:10, name:"Grand child of parent 2", pid: 7},
    {id:11, name:"Grand child of parent 2", pid: 7},
    {id:12, name:"Grand child of parent 2", pid: 8},
    {id:13, name:"Grand child of parent 2", pid: 8},
    {id:14, name:"Grand child of parent 2", pid: 8},
    {id:15, name:"Grand Child of Parent 1 ", pid: 9},
    {id:15, name:"Child of Parent 4 ", pid: 4},
    ]

Nested Loop and Condition:

    render() {
    let subMenu='';
    let ssubmenu='';
    const newMenu = this.state.menus.map((menu)=>{
    if (menu.pid === 0){
    return (
    <ul key={menu.id}>
       <li>
          {menu.name}
          <ul>
             {subMenu = this.state.menus.map((smenu) => {
             if (menu.id === smenu.pid) 
             {
             return (
             <li>
                {smenu.name}
                <ul>
                   {ssubmenu = this.state.menus.map((ssmenu)=>{
                   if(smenu.id === ssmenu.pid)
                   {
                   return(
                   <li>
                      {ssmenu.name}
                   </li>
                   )
                   }
                   })
                   }
                </ul>
             </li>
             )
             }
             })}
          </ul>
       </li>
    </ul>
    )
    }
    })
    return (
    <div>
       {newMenu}
    </div>
    );
    }
    }

Just Tried that:

return(
  <>
    {
      main-condition-1 && 
      main-condition-2 &&
      (sub-condition ? (<p>Hi</p>) : (<p>Hello</p>))
     }
  </>
)

Let me know what you guys think!!!


In two ways we can solve this problem:

  1. Write a else condition by adding just empty <div> element.
  2. or else return null.
render() {
    return (   
        <View style={styles.container}>
            if (this.state == 'news'){
                return (
                    <Text>data</Text>
                );
            }
            else {
                 <div> </div>
            }

        </View>
    )
}

I do like this and its working fine.

constructor() {
   super();

   this.state ={
     status:true
   }
}

render() {
   return( 

     { this.state.status === true ?
           <TouchableHighlight onPress={()=>this.hideView()}>
             <View style={styles.optionView}>
               <Text>Ok Fine :)</Text>
             </View>
          </TouchableHighlight>
           :
           <Text>Ok Fine.</Text>
     }
  );
}

hideView(){
  this.setState({
    home:!this.state.status
  });
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to react-native

How to resolve the error on 'react-native start' React Native Error: ENOSPC: System limit for number of file watchers reached How to update core-js to core-js@3 dependency? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 How can I force component to re-render with hooks in React? What is useState() in React? Getting all documents from one collection in Firestore ReactJS: Maximum update depth exceeded error React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH