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

Best way too check the false & true condition in React Js

what is the best way to check the false & true condition in this case, i have a state set to false initially

status: false,

The status changes to true if a certain props is present (data-widget) do i need to add the ="true" to the attribut?

<div id="app" data-widget></div>
// Is it the same thing or i don't need to add the ="true" to the attribut
<div id="app" data-widget="true"></div>

Here is how i check a condition, i am confused which one i should use :

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

//Option 1
newData.status = this.props.widget ? true : false
//Option 2
newData.status = (typeof this.props.widget !== "undefined") ? true : false

Is there a better/correct way to handle the false & true condition?

>Solution :

Is there a better/correct way to handle the false & true condition?

There’s no "the best" way, it all depends on conditions. Even if they are looking similar they strongly differ. The first option will evaluate to true if props.widget is truthy – (it’s either an array, object, true, number (different that 0) or a non-empty string.

However the second one will evaluate to true if props.widget is not equal to undefined. It will evaluate to false ONLY if props.widget is undefined.

Anyways, if it’s acceptable for your conditions, I would go with simple checking the truthyness of props.widget:

newData.status = Boolean(this.props.widget); // will evaluate to true or false
                                             // with no need to use ternary
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