'Else if statement inside return in React Native
I'm newbie in react-native
, and I have a problem with how to make else if inside the return, currently I have error which says, and I want to else if the ScanResult if statement was true.
false is not a function (near`...Statement is true"))(ScanResult && _reac...`)
This is just example but I have a button which changes the boolean status of useState. Thanks is advance badly need help
const [scan, setScan] = useState(false);
const [ScanResult, setScanResult] = useState(false);
const [result, setResult] = useState(null);
{(scan && (
<Text>Statement is true</Text> //if true goes here
))
(ScanResult && (
<Text>Scan Result is true</Text> //else if true goes here
))
|| (
<Text>Statement is false</Text> //else goes here
)}
Solution 1:[1]
I would do it like so:
const [scan, setScan] = useState(false);
const [ScanResult, setScanResult] = useState(false);
const [result, setResult] = useState(null);
return (scan ? <Text>Statement is true</Text> : ScanResult ? <Text>Scan Result is true</Text> : <Text>Statement is false</Text>)
Solution 2:[2]
If you want to display both texts if both scan
and ScanResult
are true and the last statement otherwise, you need a parent element. Try to wrap everything inside a fragment and use the following code.
return (
<>
{scan && <Text>Statement is true</Text>}
{ScanResult && <Text>Scan Result is true</Text>}
{!scan && !ScanResult && <Text>Statement is false</Text>}
</>
)
If scan
is equal to true, it renders Statement is true
. If ScanResult
is true, it renders Scan Result is true
. If both flags are false, it renders Statement is false
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | David Scholz |