Ternary Operator in React.js

JavaScript-World
2 min readMay 23, 2023

--

Photo by Lautaro Andreani on Unsplash

In JavaScript, the ternary operator provides a quick and concise way to write if…else statements. This operator is frequently used in React.js to dynamically render components based on conditions. This article aims to familiarize you with the basics of the ternary operator and provide examples of its use within the context of React.js.

Introduction to the Ternary Operator

In JavaScript, the ternary operator is a decision-making operator that returns one value if the condition is true, and another if the condition is false. The syntax is as follows:

condition ? value_if_true : value_if_false;

For example, let’s declare a variable isReactFun that holds a Boolean value. We'll then use the ternary operator to assign a message based on this Boolean value.

let isReactFun = true;
let message = isReactFun ? 'React is fun!' : 'React is not fun.';

console.log(message); // "React is fun!"

The Ternary Operator in React.js

The ternary operator is incredibly useful in React.js as it allows us to dynamically render components based on the state or props of our components. Let’s consider an example:

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { isReactFun: true };
}

render() {
return (
<div>
{this.state.isReactFun ? <h1>React is fun!</h1> : <h1>React is not fun.</h1>}
</div>
);
}
}

In the above example, we use the ternary operator to render a different <h1> tag based on the value of this.state.isReactFun.

Advanced Use Cases

As we progress, ternary operators can be nested for multiple conditions. Here’s an example:

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { mood: 'happy' };
}

render() {
return (
<div>
{this.state.mood === 'happy' ? <h1>I'm happy!</h1> :
this.state.mood === 'sad' ? <h1>I'm sad.</h1> :
<h1>I'm okay.</h1>}
</div>
);
}
}

In this example, we check the state mood and render different headings based on its value.

Motivational Quote

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” — Martin Fowler

If you enjoyed the article and would like to show your support, be sure to:

👏 Applaud for the story (50 claps) to help this article get featured

👉Follow me on Medium

Check out more content on my Medium profile

--

--

JavaScript-World

Elevating web experiences with 10+ yrs in JS🚀.Crafting seamless UIs,optimizing performance, mentoring next-gen coders.Passionate about learning&innovation.🌐✨