Home > front end >  Else if statement inside return in React Native
Else if statement inside return in React Native

Time:05-14

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

CodePudding user response:

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>)

CodePudding user response:

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.

  • Related