I know that boolean props can be passed to a React component as true
or false
simply by their presence or absence (as per React JSX documentation and this answer by Artif3x in this StackOverflow question.
So, I might have something like <MyEvent isRecurring />
which passes the isRecurring
prop as true
, whereas <MyEvent />
would see isRecurring
as false
(or undefined).
Is it possible to pass a prop with no value (so, it's presence means it is true
) when the name of the prop is dynamic (stored in a variable)?
For example, this does not work:
const propToSetToTrue = someCondition ? 'isRecurring' : 'isArchived'
<MyEvent {propToSetToTrue} /> // Syntactically, not allowed
And, to use object spread, I need to set the prop equal to something (naturally, that would be true
). This does work, but it's not exactly what I am looking for:
// Assume props already populated at this point
const propToSetToTrue = someCondition ? 'isRecurring' : 'isArchived'
props[propToSetToTrue] = true // This works, but it's not ideal
<MyEvent {...props} />
Use Case
I've gotten a few comments asking why I might need this. Here is a possible use case, in testing:
// sharedExamples/props.js
function textDependsOnProp(Component, propName, testId) {
it(`sets text to 'FOO' when prop '` + propName + `' is given'`, () => {
const { queryByTestId } = render(<Component {propName} />) // This does not work
expect(queryByTestId(testId).textContent).toEqual('FOO')
})
it(`sets text to 'BAR' when prop '` + propName + `' is not given'`, () => {
const { queryByTestId } = render(<Component />)
expect(queryByTestId(testId).textContent).toEqual('BAR')
})
}
My tests are in the process of being refactored to be used for many different components, and the actual prop name to focus on may be different for each component, which is why the prop name is dynamic.
So, should I just forget about what I thought was ideal and just explicitly set my prop to true, like so:
const props = {}
props[propName] = true
render(<Component {...props} />)
It just felt like 2 extra lines of code for something I thought could be trivial.
Or is there a way to do it similar to what I've written above?