Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write if condition with two statement in React Native

I am just confused about how to match two statement like if else of JavaScript in React Native

for e.g.,

if(array.length != null && array.length >= 2){
    alert("Array Is Greater Than 2")
}else if(array.length != null ){
    alert("Array Is Less Than 2")
}else{
    alert("Array is null")
}

I know how to pass signle condition in React Native like

for e.g.,

{
    array.length != null &&
    <View>
        /* Content Here */
    </View>
}

or

{
    array.length != null ?
    <View>
        /* If Content Here */
    </View>
    :
    <View>
        /* Else Content Here */
    </View>
}

But How do I create if state like first one ?

like image 215
Kirankumar Dafda Avatar asked Jul 10 '18 09:07

Kirankumar Dafda


2 Answers

You can have nested ternary condition check like

{
    array.length != null && array.length >= 2 ?
    <View>
        /* If Content Here */
    </View>
    :
    array.length != null?
     <View>
        /* Else if Content Here */
    </View>: 
    <View>
        /* Else Content Here */
    </View>
}

However you can simply do it using if-else in a function which you call from render as suggested by @MayankShukla since it is more readable then nested ternary operators

like image 165
Shubham Khatri Avatar answered Sep 19 '22 20:09

Shubham Khatri


You can have nested ternary conditions, but i will not suggest that because it will be not that readable. Other option is you can put all those conditions inside a function and call that function from render method.

Like this:

renderElement () {
    if(array.length != null && array.length >= 2){
        alert("Array Is Greater Than 2");
        return <p>If condition</p>;
    }else if(array.length != null ){
        alert("Array Is Less Than 2");
        return <p>If-Else condition</p>;
    }else{
        alert("Array is null");
        return <p>Else condition</p>;
    }
}

render () {
    const element = this.renderElement();
    // now you can use element to render that element at any place
}

Nested ternary conditions:

{
    array.length != null && array.length >= 2 ?
        <View>
            /* Array Is Greater Than 2 */
        </View>
    :
        array.length != null?
            <View>
                /* Array Is Less Than 2 */
            </View>
        :
            <View>
                /* Array Is Null */
            </View>
}
like image 45
Mayank Shukla Avatar answered Sep 18 '22 20:09

Mayank Shukla