Given the following JSX:
const elems = <div><p>hello</p><p>world</p></div>
If I want to add another element to the end, is there a more idiomatic way than doing:
const moreElems = <div>{elems}<p>additional</p></div>
Maybe something like:
elems.push(<p>additional</p>)
I would be fine omitting the wrapper div
; that's just so there's only a single top-level JSX element.
You can do that by declaring the first elements in an array:
const elements = [
<p>hello</p>,
<p>world</p>,
]
And then pushing whatever you want to the array:
elements.push(<p>Additionnal</p>)
You can then use this element using {elements}
anywhere you want.
Bear in mind that this array notation would require you to use a key
parameter in each of these childs, so something like this would be better:
const elements = [
<p key="1">hello</p>,
<p key="2">world</p>,
]
elements.push(<p key="3">additionnal</p>)
You can always have them pushed into an array and then wrap the array in a div and react will handle it appropriately something like:
const phrase = [];
phrase.push(<p key="hello">hello</p><p>world</p>)
phrase.push(<p key="additional">additional</p>)
return <div> {phrase} </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With