Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '&&' operator indicate with { this.props.children && React.cloneElement(this.props.children, { foo:this.foo})

I have react class that is rendered using react router. I understand that React.cloneElement is used to pass elements from parent to child. But why/what does the '&&' operator do with this kind of statement :

class Users extends React.Component {
    getInitialState() {
      return {
          page:0
        }
     },      
    foo(){
        this.setState({'page':1})
     }
      render() {
        return (
          <div>
            <h2>Users</h2>
            { this.props.children && React.cloneElement(this.props.children, {
    foo:this.foo})
          </div>
        )
      }
    }

I would like to understand why are we using '&&' operator here.

like image 412
Arathi Arumugam Avatar asked Nov 18 '16 16:11

Arathi Arumugam


2 Answers

It's Short circuit evaluation

(if this part is true) && (this part will execute)

And it shorthand of:

if(condition){
   (this part will execute)
}
like image 161
sadiq Avatar answered Nov 06 '22 00:11

sadiq


The && is the exact same operator as you would find in any javascript expression, such as...

if( condition1 && condition2) {

}

It is a feature of javascript that an expression of the form...

(condition1 && condition2)

will evaluate to condition2, if condition1 is true, or null if condition1 is false. It is effectively shorthand for...

if(condition1) {
    condition2;
}

We use this shorthand by placing a React element as condition 2, getting...

(condition1 && <ReactElement />)

which is effectively...

if(condition1) {
    <ReactElement />
}
like image 22
Alex Young Avatar answered Nov 06 '22 01:11

Alex Young