React-Native How to use a Boolean
Solution 1
This is more a JS question than an React Native one, since React Native uses standard-compliant JavaScript as programming language. So, going through all your questions:
Where in my code do I have to declare the boolean?
The boolean is one of the 6 data type primitives in JS, along with null, undefined, number, string and Symbol (ES6 only). So you can just create a boolean the way you would with any of those. For instance:
var myBoolean = true;
You can create the boolean in pretty much any part of your code: inside a function, as a global variable, as an object property...
Remember than JS is a dynamically weakly typed language, which means that if you assign a different type value to myBoolean
, it would then be of that type. For instance:
var myBoolean = true; // I'm a boolean
myBoolean = "A string"; // I'm a string
How can I change the value?
We just changed its value by initializing the variable, but it would be as simple as:
var myBoolean = true; // I'm a boolean
myBoolean = false;
What is the right way to compare it ? (I think if(myBoolean===true) but I am not completely sure.)
Your approach is totally correct, but you can also do some other things in this case. This are all valid:
if(myBoolean === true) // Will check that myBoolean has the same value and type as true
if(myBoolean == true) // Will check that myBoolean has the same value as true
if(myBoolean) // Will check that myBoolean has a 'truthy' value (anything that is not a false, 0, "", null, undefined or NaN (not a number).
Solution 2
martinarroyo's answer is fantastic, but just to add:
React Native uses JSX (XML + JavaScript).
When using JSX, always encapsulate booleans in curly braces:
<View>
<MapView
showsUserLocation={true}
>
</Mapview>
</View>
You can also do some interesting things with JSX, like conditionally render components:
<View>
// This component will render
<TouchableHighlight>
{true}
</TouchableHighlight>
// This component will not render
<TouchableHighlight>
{false}
</TouchableHighlight>
</View>
More information here: https://facebook.github.io/react/docs/jsx-in-depth.html
Michael Wall
Updated on July 09, 2022Comments
-
Michael Wall almost 2 years
I don't know how to work with a Boolean in React-Native.
I tried to find a solution on google but apparently my question is so simple that no-one has asked it.
Whereat my code do I have to declare the boolean?
How can I change the value?What is the right way to compare it? (I think if(myBoolean===true) but I am not completely sure.)