Using ternary operator in React explained with examples

Following the previous articles we talk about using ternary operator in React  with some examples.

Conditional rendering using ternary operator in React 

Of course using if else statement has been around for ages. We can always use them in conditional rendering anywhere. But using ternary operator in React is now an important alternative which is simpler and more maintainable.

Firstly have a look at this example with if/else statement:

const MyComponent = ({ name }) => {
  if (name) {
    return (
      <div className="hello">
        Hello {name}
      </div>
    );
  }
  return (
    <div className="hello">
      Please sign in
    </div>
  );
};

In this functional component of a form we simply return the name if it exists of we ask the user to put in the name. However if we use the ternary operator in React we make it look cleaner and neater just like this:

const MyComponent = ({ name }) => (
  <div className="hello">
    {name ? `Hello ${name}` : 'Please sign in'}
  </div>
);

All the if/else statement has become just one statement with the same result as above.  

In addition have a look at these examples of using ternary operator in Rect site itself:

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
    </div>
  );
}<br/>

Conditionally we are using state to check if the user is logged in in a class component. Using ternary operator in React makes it super easy and quick to obtain the result. 

Having a larger example

We could use ternary operator In JSX code. To render some JSX code conditionally we could do this as needed:

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn ? (
        <LogoutButton onClick={this.handleLogoutClick} />
      ) : (
        <LoginButton onClick={this.handleLoginClick} />
      )}
    </div>
  );
}<br/>

Remember it is best to use ternary opertor in short JSX code for having a clear and maintainable code. Thanks for reading. 

© 2019
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.