-1

Which one is the most appropriate to use in React, and why?

*NB: examples are in React jsx-syntax;

<div style={ condition ? {backgroundColor:'#d6f9dd'} : {} }>

<div style={ condition ? {backgroundColor:'#d6f9dd'} : undefined }>

<div style={ condition ? {backgroundColor:'#d6f9dd'} : null }>

<div style={ condition ? {backgroundColor:'#d6f9dd'} : 'inherit' }>

<div style={ condition ? {backgroundColor:'#d6f9dd'} : 'none' }>
joedotnot
  • 4,810
  • 8
  • 59
  • 91

2 Answers2

0

Personally, I only ever use the style property if I need to overwrite a css attribute that was attached by a separate library.

Out of the options you provided the only ones that are valid are the following:

<div style={ condition ? {backgroundColor:'#d6f9dd'} : {} } />
<div style={ condition ? {backgroundColor:'#d6f9dd'} : undefined } />

React expects the style property to be either undefined or an object.

On top of that I would conditionally apply the css properties themselves rather than the entire style object.

Like so:

<div style={{ backgroundColor: condition ? '#d6f9dd' : undefined }} />

That way if I need to apply multiple style properties but one of them depends on the condition, the other one can still be applied even when the condition is not true. Setting a property to undefined is akin to never having included it in the style object at all.

Abir Taheer
  • 2,502
  • 3
  • 12
  • 34
  • I think this will also work, all: unset is valid css – joedotnot Nov 06 '21 at 03:27
  • @joedotnot if you have some global css file or external library that applies a css property to the div or something like that, setting the style property to `unset` will remove the effects of of those styles too. – Abir Taheer Nov 06 '21 at 03:46
0

Don't use empty objects. They can return truthy, as well as having properties.

console.log(typeof {}.hasOwnProperty); // function

This might cause problems down the line. The best option is using undefined if want inline styling imo

OMGItsRob
  • 105
  • 1
  • 2
  • 7