react

How to use ternary operator in React


In this article, you will learn about how to use the ternary operator in React.

A ternary operator is a kind of operator that takes three operands and helps programmers to make decisions. It is a shorter form of the if-else conditional statement. As it takes three operators, it is called the ternary operator. Before jumping into how you can use the ternary operator in react, let’s see an example of a ternary operator in JavaScript first:

let x = 20
let y = 10

const result = (x > y) ? x : y;

console.log(result)
// Output: 20

ReactJS is a free and open-source JavaScript library that is used in the front-end to make more interactive UI. As you can see it is a JavaScript library then it is obvious you can write JavaScript code here. Now the question is how you can write JavaScript code here. The logic and use-case of the ternary operator are the same. Let’s see how you can implement ternary operator in react in the following example:

JavaScript

import {useState} from 'react'
import "./index.css"


function App() {

  const [toggle,setToggle] = useState(false)

  const toggleFunc = () => {
    setToggle(!toggle)
  }

  return (
    <div className={toggle ? 'container salmon' : 'container'}>
      <button className='btn' onClick={toggleFunc}>Toggle</button>
    </div>
    
  );
}

export default App;

Here, we simply take a function name toggle and a button. We have given some styles in the container and the color of the container will be changed based on the click of the toggle button. You can notice that we simply write one line of code by using a ternary operator and that is when the toggle functions return true then it will give one color and when it returns false then it will give another color. If you try to implement this condition by using an if-else statement then the code will look messy. This is the beauty of a ternary operator and this operator is widely used in react.

CSS

.container {
    max-width: 500px;
    background-color: steelblue;
    padding: 30px;
    border-radius: 5px;
    margin: 0px auto;
}
.container.salmon {
    background-color: salmon;
}

Here, we simply style our container to look it better. Let’s check the output below if our program is working perfectly or not.

Output

ternary operator in React

By default, our container will look like this. Now let’s click on the toggle button and see if things are changing or not in below:

ternary operator in React

You can notice that when we have clicked on the toggle button the color changed to salmon that is set by us. It means our program is working perfectly. If you click again on the toggle button, the toggle function will return false and our first design will show in the display.

The ternary operator is essential and widely used in react. In this example, you may get familiar with how to use this operator in react.


Share on social media

//