code-jaff code-jaff - 2 months ago 19
Javascript Question

How to pass props without value to component

How does one pass a prop without value to a react component?

<SomeComponent disableHeight> {/* here */}
{({width}) => (
autoHeight {/* and here */}

Note - there is no default prop values specified for those props.

I can't seem to find any references on that, but by observing values for those properties they get assigned to
by default.


What you are passing is interpreted by the compiler as a boolean attribute. This is also true for when writing pure HTML; attributes without values are interpreted as a boolean true. Since JSX is a syntactic-sugar for writing HTML, it makes sense that it has the same behavior.

The official React documentation has the following:

Boolean Attributes

This often comes up when using HTML form elements, with attributes like disabled, required, checked and readOnly. Omitting the value of an attribute causes JSX to treat it as true. To pass false an attribute expression must be used.

// These two are equivalent in JSX for disabling a button

<input type="button" disabled />;
<input type="button" disabled={true} />;

// And these two are equivalent in JSX for not disabling a button

<input type="button" />;
<input type="button" disabled={false} />;



  <Component autoHeight />
  <AnotherComponent autoHeight={null} />


  React.createElement(Component, { autoHeight: true }),
  React.createElement(AnotherComponent, { autoHeight: null })

Check the babel demo of this, here.


As ctrlplusb stated, if you want to pass an "empty prop" you can simply give it the value of null.

So you could do:

<SomeComponent disableHeight={null}>
    {({width}) => (

Though I will note that this is probably entirely unnecessary because reading this.props.autoHeight from AnotherComponent will always give you null, regardless if you explicitly passed it as autoHeight={null} or not at all.