I'm trying to clarify some confusion I have about boolean props in React.
Suppose a have MyComponent
with several boolean props prop1
, prop2
...
First: it seems that boolean props are like just others: you can define default values, either in defaultProps or in destructuring params:
const MyComponent = ({ prop1, prop2 }) => (
...
);
MyComponent.defaultProps = {
prop1: false,
prop2: true,
}
Or (equivalently... I think)
const MyComponent = ({ prop1 = false, prop2 = true }) => (
...
)
What's not clear is how to pass values. The natural "React style", again, seems to be
<MyComponent prop1={ BOOLEAN_EXPRESION1 } prop2={ BOOLEAN_EXPRESION2 } />
... including the static literals (false/true
).
However, it's also stated that the correct (recommended?) way to pass boolean properties is presence/absence of the attribute, as in HTML5.
So that, instead of <MyComponent prop1={true} prop2={false} />
, one should write <MyComponent prop1 />
.
My questions are:
What is the correct way of passing boolean props? Are both acceptable?
In case HTML5 style is the recommended (or correct) way, how would one deal with dynamic values?
In case HTML5 style is acceptable, what about default values? In the example above (where
prop2
istrue
by default), if I write<MyComponent />
, what value wouldprop2
get?
Edit: To the accepted answer, I'd like to add my own tip: to play along nicely with the HTML5 style (and to prevent surprises), design your boolean props so that they are by default false
. Put in other way: a boolean prop that defaults to true
should be considered an antipattern.
Edit 2: It should be noted that sometimes the default of a boolean prop is undefined
and that's (by design) treated differently than false
, (eg: in Material UI's Checkbox the prop checked
is true|false
if the component is controlled, undefined
if it's uncontrolled). Hence here the HTML5 convention cannot be used.