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
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.
1 | <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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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:
Thank you for reading. Happy Coding!