Conditionally add attributes to React components

avatar

Borislav Hadzhiev

Last updated: May 1, 2022

banner

Photo from Unsplash

Conditionally add attributes to React components #

Use the ternary operator to conditionally add attributes to React components, e.g. <button disabled={count > 3 ? true : null}>. If the value to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise it returns the value to the right.

App.js
import './App.css'; import {useState} from 'react'; export default function App() { const [count, setCount] = useState(0); const role = 'link'; let myClass = ''; if (count >= 0) { myClass = 'bg-salmon'; } return ( <div> {/* 👇️ conditionally set attribute value with ternary operator */} <button disabled={count > 3 ? true : null} onClick={() => setCount(current => current + 1)} > Count: {count} </button> {/* 👇️ using a variable */} <a href="https://google.com" role={role}> Google.com </a> {/* 👇️ interpolating a variable */} <h2 className={`text-white ${myClass}`}>Some content</h2> </div> ); }

And here is the css for the examples in this article.

App.css
.bg-salmon { background-color: salmon; } .text-white { color: white; }

react conditionally set attributes

The first example in the code snippet uses the ternary operator to conditionally set an attribute on an element.

App.js
<button disabled={count > 3 ? true : null} onClick={() => setCount(current => current + 1)} > Count: {count} </button>

The code checks if the count variable is greater than 3 and if it is, it returns true for the disabled attribute, otherwise null is returned.

You can also use logic outside of your JSX code and then use a variable to set the attribute.

App.js
import './App.css'; export default function App() { const role = 'link'; let myClass = ''; if ('hi'.length >= 0) { myClass = 'bg-salmon'; } return ( <div> {/* 👇️ using a variable */} <a href="https://google.com" role={role}> Google.com </a> {/* 👇️ interpolating a variable */} <h2 className={`text-white ${myClass}`}>Some content</h2> </div> ); }

You can use any logic you need when setting the myClass variable and then use it when setting an attribute.

Every time the component rerenders, your logic will run and update the variable's value.

You can also create an object containing attribute names and values and then use the spread syntax (...) to set the props on the element.

App.js
import {useState} from 'react'; export default function App() { const [count, setCount] = useState(0); const attrs = {}; if ('hi'.length === 2) { attrs.role = 'button'; attrs.onClick = () => { setCount(current => current + 1); }; } return ( <div> <button {...attrs}>Count: {count}</button> </div> ); }

We initialized an empty object and then conditionally set properties on it.

The spread syntax (...) is then used to unpack all of the key-value pairs from the object and set them as props on the element.

You can use any logic and conditionals in order to build the object.

You will most commonly use the ternary operator to add conditional attributes to an element in React.

Here is an example that conditionally sets an element's display property.

App.js
import {useState} from 'react'; export default function App() { const [isShown, setIsShown] = useState(true); const handleClick = event => { // 👇️ toggle visibility setIsShown(current => !current); }; return ( <div> <button onClick={handleClick}>Toggle visibility</button> <div style={{display: isShown ? 'block' : 'none'}}> <h2>Some content here</h2> </div> </div> ); }

The display property of the style prop of the div element is conditionally set using a ternary operator.

If the value to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise the value to the right of the colon is returned.

App.js
const result1 = 5 === 5 ? 'yes' : 'no'; console.log(result1); // 👉️ "yes" const result2 = 5 === 10 ? 'yes' : 'no'; console.log(result2); // 👉️ "no"

If the isShown state variable stores a truthy value, we set the display property to block. Otherwise, it's set to none.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.