Home > Blockchain >  Javascript inline style in React - null, undefined, empty-Object, inherit, or none?
Javascript inline style in React - null, undefined, empty-Object, inherit, or none?

Time:11-07

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' }>

CodePudding user response:

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.

CodePudding user response:

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

  • Related