Haider Ali Anjum
Haider Ali Anjum

Reputation: 847

How does a javascript && operator work

I want to pass a prop to a React Component, conditional to a boolean in parent component's state, The component expects to have myProp as an object, the propTypes conflagration is bellow:

//component's code
class MyComponent extends Component {

    ...
    static propTypes = {
        myProp: propTypes.object
    }
    ...
}

Now, I am on to pass the prop like below:

//Parent component's code
class ParentComponent extends Component {
    constructor() {
        super();
        this.state = {
          par: true,
        }
    }
    render(){
        const obj = {
            key1: 'value1',
            key2: 'value2'
        }
        ...
        return ( 
            <MyComponent
                myProp = {this.state.par && obj}
            />
        )
    }
...
}

Executing the above code it gives me following warning in browser console:

Warning: Failed prop type: Invalid prop myProp of type boolean supplied to MyComponent, expected object.

Upvotes: 1

Views: 288

Answers (3)

Shubham Khatri
Shubham Khatri

Reputation: 281726

In your case myProp = {this.state.par && obj} if this.state.par is false and obj is present then boolean value false will be returned instead of obj, you should write it like

myProp = {this.state.par? obj: null}

As per the docs:

true && expression always evaluates to expression, and false && expression always evaluates to false.

Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.

Upvotes: 4

Jason
Jason

Reputation: 11363

I would include the boolean as a property inside the obj and check for the value inside the child component

render() {
   const obj = {
        key1: 'value1',
        key2: 'value2'
        par: this.state.par
    }
   return(
       <MyComponent myProp={obj} />
   );
}

and handle the true/falsiness in the child component.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074385

If this.state.par is false, then this.state.par && obj is false (boolean, not object).

You may want the conditional operator instead:

return ( 
    <MyComponent
        myProp = {this.state.par ? obj : null}
    />
)

Now, regardless of the flag, you're providing something of type object (obj or null).

Or somewhat more obscurely, add a ||:

return ( 
    <MyComponent
        myProp = {this.state.par && obj || null}
    />
)

...but I'd use the conditional.


Of course, MyComponent will need to understand that myProp may be null...

Upvotes: 1

Related Questions