Ternary Operator in 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
- If Else Statement in ReactJS
- Element Variables in ReactJS
- Scroll to the top of the page after render in ReactJS
- API call in React JS
- Nested Routes in React JS
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
Thank you for reading. Happy Coding!