Clue Mediator

Ternary Operator in ReactJS

πŸ“…January 7, 2020
πŸ—ReactJS

Today we will show you the example of the ternary operator in ReactJS. It’s also know as conditional operator. If you want to conditionally render the small block of the text then you can use the ternary operator / conditional operator in React JS.

Ternary Operator in ReactJS, Example to use a ternary expression for conditional rendering, react conditional render multiple elements from props, Use a Ternary Expression for Conditional Rendering, react switch case.

Checkout more articles on ReactJS

Example of Ternary Operator

Let's refer to the same example of the previous article where we will update the text of the button on the click event of it.

Refer previous article: Prevent Component from Rendering in ReactJS

Here we will change the button text from β€œToggle Tab” to β€œShow Tab” or β€œHide Tab” with the help of ternary operator. Your button code should look like below.

<input type="button" value={`${showTab ? 'Hide' : 'Show'} Tab`} onClick={handleToggle}></input>

After changing the code in button element, your `App.js` file should be same as below.

App.js

import React, { useState } from 'react';
import tab from './Tab';

const App = () => {

  const [showTab, setShowTab] = useState(true);

  // handle click event of the toggle button
  const handleToggle = () => {
    setShowTab(preState => !preState);
  }

  return (
    <div className="App">
      <div style={{ marginBottom: 10 }}><a href="https://www.cluemediator.com" target="_blank">Clue Mediator</a></div>
      <input type="button" value={`${showTab ? 'Hide' : 'Show'} Tab`} onClick={handleToggle}></input>
      {tab(showTab)}
    </div>
  );
}

export default App;

Here we have changed the code in only single file (App.js), everything else will remain the same.

Output:

Output - Ternary Operator in ReactJS - Clue Mediator

Output - Ternary Operator in ReactJS - Clue Mediator

Thank you for reading. Happy Coding!

Demo & Source Code

Github Repository StackBlitz Project