Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript inline style in React – null, undefined, empty-Object, inherit, or none?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading