Using ternary operator in Inline styles in React

avatar

Borislav Hadzhiev

Tue Apr 26 20222 min read

Using ternary operator in Inline styles in React #

To use the ternary operator in inline styles in React:

  1. Conditionally check when setting a specific property in the style object.
  2. Conditionally check when setting the value for the style prop.
App.js
import {useState} from 'react'; const App = () => { const [count, setCount] = useState(0); return ( <div> <h2 style={{ backgroundColor: count > 0 ? 'lime' : 'salmon', color: count > 0 ? 'white' : 'powderblue', }} > Count: {count} </h2> <h2 style={ count > 0 ? {backgroundColor: 'lime', color: 'white'} : {backgroundColor: 'salmon', color: 'powderblue'} } > Count: {count} </h2> <button onClick={() => setCount(current => current + 1)}> Increment </button> </div> ); }; export default App;

react style ternary

The first example shows how to use the ternary operator to check for a condition when setting the value of a specific CSS property in the element's styles.

The ternary operator is very similar to an if/else statement.

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

In the first example, we check if the count variable stores a value greater than 0. If it does, we set the backgroundColor property to lime, otherwise we set it to salmon.

App.js
<h2 style={{ backgroundColor: count > 0 ? 'lime' : 'salmon', color: count > 0 ? 'white' : 'powderblue', }} > Count: {count} </h2>

You can also use the ternary operator to conditionally set a value for the entire style prop.

App.js
<h2 style={ count > 0 ? {backgroundColor: 'lime', color: 'white'} : {backgroundColor: 'salmon', color: 'powderblue'} } > Count: {count} </h2>

When we use the style prop, we have 2 sets of curly braces. The outer set indicates to React that we have an expression that has to be evaluated.

The inner set of curly braces is the object of CSS properties and values.

If you have multiple properties whose values are determined by the same condition, you could use the ternary operator to return an entire object of properties and values.

However, you could also extract the condition into a variable and use the first approach.

App.js
const isGreaterThan0 = count > 0; // ... <h2 style={{ backgroundColor: isGreaterThan0 ? 'lime' : 'salmon', color: isGreaterThan0 ? 'white' : 'powderblue', }} > Count: {count} </h2>

Which approach you pick is a matter of personal preference. I find this easier to read than returning an entire object from the ternary operator because I can clearly see which properties are dependent on the condition.

Use the search field on my Home Page to filter through my more than 1,000 articles.