How can I pass a prop only to the first element in an array of React elements of unknown elements? For example, in the following snippet, elements
is an array of up to 3 customized Bar
elements, and I would like only the first to be passed an arbitrary prop.
function Foo(props) {
const myProp = 'test';
const elements = [
(isP && <Bar prop1={'p'} />),
(isQ && <Bar prop1={'q'} />),
(isR && <Bar prop1={'r'} />),
].filter(x => x);
// Now do something like 'elements[0].props.myProp = myProp'
return elements;
}
The context for this is that I'd like to show three panels in a sidebar. The first should show its title and body, and the others should only show their title.
Some solutions I've considered but don't like:
1) Use React's cloneElement
method to clone the first element and pass it a prop. 1 But it seems like poor form to clone a React element just to set a single prop.
2) Preprocess the boolean logic to determine which element would be first, and then assign the prop. For example, something like the code below except with more clever logic:
function Foo(props) {
const myProp = 'test';
const elements = [
(isP && <Bar myProp={isP && myProp}/>),
(isQ && <Bar myProp={!isP && isQ && myProp} />),
(isR && <Bar myProp={!isP && !isQ && isR && myProp} />),
].filter(x => x);
return elements;
}
Ideally, the solution would accomplish the goal efficiently and concisely. If there is no better solution than (1) or (2) though, I'd also accept that as an answer.
EDIT: some points I forgot to clarify.
- I am using Redux in case that's helpful to take into account.
- The instances of
<Bar />
actually are multiple types (e.g.Bar
,Bas
,Baz
) in case that materially affects the answer. (I mistakenly oversimplified the original question.)