if-else statement inside jsx: reactjs

  • Last Update :
  • Techknowledgy :

JSX is fundamentally syntactic sugar. After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects. We can embed any JavaScript expression in JSX by wrapping it in curly braces. But only expressions not statements, means directly we can not put any statement (if-else/switch/for) inside JSX. 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:

This is our Splunktool team suggestion ✌, we tried and its working fine
render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn
        ? <LogoutButton onClick={this.handleLogoutClick} />
        : <LoginButton onClick={this.handleLoginClick} />
      }
    </div>
  );
}

If you want to render the element conditionally then use ternary operator, like this:

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

Another option is, call a function from jsx and put all the if-else logic inside that, like this:

renderElement(){
   if(this.state.value == 'news')
      return <Text>data</Text>;
   return null;
}

render() {
    return (   
        <View style={styles.container}>
            { this.renderElement() }
        </View>
    )
}

Suggestion : 2

This means that if statements don't fit in. Take this example: If a ternary expression isn't robust enough, you can use if statements outside of your JSX to determine which components should be used: Or if you prefer a more "inline" aesthetic, define immediately-invoked function expressions inside your JSX: In the example above, an ES6 arrow function is utilized to lexically bind the value of this.

1._
// This JSX:
ReactDOM.render(<div id="msg">Hello World!</div>, mountNode);

// Is transformed to this JS:
ReactDOM.render(React.createElement("div", {id:"msg"}, "Hello World!"), mountNode);
2._
// This JSX:
<div id={if (condition) { 'msg' }}>Hello World!</div>

// Is transformed to this JS:
React.createElement("div", {id: if (condition) { 'msg' }}, "Hello World!");
3._
ReactDOM.render(<div id={condition ? 'msg' : null}>Hello World!</div>, mountNode);
5._
return (
  <section>
    <h1>Color</h1>
    <h3>Name</h3>
    <p>{this.state.color || "white"}</p>
    <h3>Hex</h3>
    <p>
      {(() => {
        switch (this.state.color) {
          case "red":   return "#FF0000";
          case "green": return "#00FF00";
          case "blue":  return "#0000FF";
          default:      return "#FFFFFF";
        }
      })()}
    </p>
  </section>
);

Suggestion : 3

Another method for conditionally rendering elements inline is to use the JavaScript conditional operator condition ? true : false. Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them. You may embed expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical && operator. It can be handy for conditionally including an element:

1._
function UserGreeting(props) {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting(props) {
  return <h1>Please sign up.</h1>;
}
2._
function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {    return <UserGreeting />;  }  return <GuestGreeting />;}
const root = ReactDOM.createRoot(document.getElementById('root')); 
// Try changing to isLoggedIn={true}:
root.render(<Greeting isLoggedIn={false} />);
3._
function LoginButton(props) {
  return (
    <button onClick={props.onClick}>
      Login
    </button>
  );
}

function LogoutButton(props) {
  return (
    <button onClick={props.onClick}>
      Logout
    </button>
  );
}
5._
function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&        <h2>          You have {unreadMessages.length} unread messages.        </h2>      }    </div>
  );
}

const messages = ['React', 'Re: React', 'Re:Re: React'];

const root = ReactDOM.createRoot(document.getElementById('root')); 
root.render(<Mailbox unreadMessages={messages} />);
6._
render() {
  const count = 0;  return (
    <div>
      {count && <h1>Messages: {count}</h1>}    </div>
  );
}

Suggestion : 4

You cannot use if-else statements inside JSX. If you want to check conditions inside JSX, use the ternary operator or put the conditional logic into a function and call that function from JSX. If you take a closer look at the resulted element, you will see there is no place for if-else statements. Therefore, we have two options when it comes to if-else inside JSX. Suitable for complex and lengthy if-else statements. The below code demonstrates how to use a function call to display a JSX element conditionally.

1._
import { ReactNode } from "react";
import { Alert } from "react-bootstrap";
interface ButtonProps {
  props: StyleProps,
  children: ReactNode
}
interface StyleProps {
  variant: string,
}
const Message = ({props, children}: ButtonProps) =>{
  return(
     <div>
        <Alert variant={props.variant}>
        {children}
        </Alert>
     </div>
  )
}
export default Message
2._
<Message props={{variant: "success"}}>
   Great Job!
</Message>
3._
React.createElement(Message, {
   props: {
      variant: "success"
   }
}, "Great Job!")
5._
React.createElement(Message, {
   props: {
      variant: "success"
   }
}, React.createElement(Alert, {
   variant: props.variant
}, children))
6._
{
    score === 100 ? 
      <Message props={{variant: "success"}}>Great Job!</Message> 
      : 
      <Message props={{variant: "info"}}>Good Job!</Message>
}

Suggestion : 5

if-else statements don’t work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. if/else. Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if, and let React update the UI to match them. We use an if with our condition and return the element to be rendered.05-Aug-2022 Another approach, which includes several samples of code, can be utilised to resolve the identical problem How To Use If Else Inside Jsx In React. This solution is explained below.

In this session, we are going to try to solve the How To Use If Else Inside Jsx In React puzzle by using the computer language. The code that follows serves as an illustration of this point.

render () {
  return (
    <div>
      {(() => {
        if (someCase) {
          return (
            <div>someCase</div>
          )
        } else if (otherCase) {
          return (
            <div>otherCase</div>
          )
        } else {
          return (
            <div>catch all</div>
          )
        }
      })()}
    </div>
  )
}
2._
renderElement(){
   if(this.state.value == 'news')
      return <Text>data</Text>;
   return null;
}

render() {
    return (   
        <View style={styles.container}>
            { this.renderElement() }
        </View>
    )
}
3._
render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.    </div>
  );
}

Suggestion : 6

An if…else statement will execute the actions contained in the if block when the condition is satisfied. Otherwise, it will execute the actions contained in the else block. This is the process of creating an extracted function. This code extracts the logic from JSX into a function renderAuthButton. And the function is executed within the JSX curly braces. Warning: This is an example of code that will not work properly. It is presented as an example of the limitations of interpretation in the render() method.

Consider an application that requires a user to log in. If the user is logged out, it will display a Login button. If the user is logged in, it will display a Logout button.

Start with using create-react-app to generate a React App:

npx create - react - app react - conditional - rendering - example

Change into the new project directory:

cd react - conditional - rendering - example

Next, open the App.js file in your code editor. And replace the contents with the following lines of code:

import React, { Component } from "react";
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoggedIn: true
    };
  }

  render() {
    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering in React.
        </h1>
        <button>Login</button>
        <button>Logout</button>
      </div>
    );
  }
}

export default App;

Then, run the application from your terminal window:

npm start

Let’s consider if you were to attempt to use an if…else statement in the render() method:

// ...

class App extends Component {
  // ...

  render() {
    let {isLoggedIn} = this.state;

    return (
      <div className="App">
        <h1>
          This is a Demo showing several ways to implement Conditional Rendering in React.
        </h1>
        {
          if(isLoggedIn){
            return <button>Logout</button>
          } else{
            return <button>Login</button>
          }
        }
      </div>
    );
  }
}

// ...

Suggestion : 7

In react, we’ll need if statements for the one more thing, it’s the rendering. The first way that we can use is to define the conditional rendering directly in the components layout. It’s named “Conditional rendering”, but to make it simple, let’s stay with “if statement in react”. Something like this makes for a comfortable reading experience when you have complex conditions, or many children. At first glance, it seems like a JSX syntax of the separate render function approach.

1._
// The first example with the code inside functional component
function Parent(props) {
  return(
    <>
      {name === "Duomly" && (
        <DuomlyComponent/> 
      )}
    </>
  )
}

// The second example with the additional function
function renderComponent() {
  const name = 'Duomly';
  if (name === 'Duomly') {
    return 'Duomly';
  } else {
    return null;
  }
}

function Parent(props) {
  return renderComponent();
}
2._
// When.jsx
export default ({ children, condition }) => {
    const shouldRender = typeof condition === 'function'
        ? condtion()
        : !!condition

    if(!shouldRender) return null

    return children
}

// Consumer.jsx
import When from '../components/When'

export default (props) =>
    <When condition={props.whateverYouLike}>
        <p>Hello, world!</p>
    </When>

Suggestion : 8

When condition evaluates to true, the operator returns “This is True”; otherwise (when condition is falsy) it returns “This is False”. As we saw, the enum approach is more readable in comparison to the switch case statement. Objects as enum open up a plethora of options to have multiple conditional renderings. The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

Consider these two components:

LoggedInUser Component:

function LoggedInUser(props) {
  return <div>
     <h1>Welcome back! </h1>
     <span>Log out </span>
   </div>;
}

LoggedOutUser Component:

function LoggedOutUser(props) {
  return <div>
     <h1>Sign in, please! </h1>
     <span>Log out </span>
   </div>;
}

We’ll create a LoggedStatus component that displays either of these components depending on whether a user is logged in or not. A different greeting is rendered depending on the value of isLoggedInprop.

function LoggedStatus(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <LoggedInUser />;
  }
return <LoggedOutUser />;
}
ReactDOM.render(
  <LoggedStatus isLoggedIn={false} />,
  document.getElementById('root')
);

&& is a boolean operator, which essentially means “and”. For the condition to evaluate to true, both of the statements must be individually true.

Below is an interesting example. Let’s say we want to render a message saying “You have X tasks to do”. When there are no pending tasks, no message should be displayed.

function TodoComponent(props) {
  const todoList = props.todoList;
  return (
    <div>
      <h1>Hi User!</h1>
      {todoList.length > 0 &&
        <h2>
          You have {todoList.length} Tasks to do.
        </h2>
      }
    </div>
  );
}
const todo = ['Eat', 'Play', 'Read'];
ReactDOM.render(
  <Task todoList={todo} />,
  document.getElementById('root')
);

Interestingly, we can write switch case inline just like normal Javascript for conditional rendering in React. However, you would need a self-invoking JavaScript function. Take a look at the implementation below.

function Notification({ param }) {
  return (
    <div>
      {(function() {
        switch(param) {
         case 'foo':
          return 'bar';
         default:
          return 'foo';
         }
        }
      })()}
    </div>
  );
}