Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  137] [ 4]  / answers: 1 / hits: 33038  / 7 Years ago, tue, march 14, 2017, 12:00:00

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.


More From » reactjs

 Answers
91

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>)

[#58551] Sunday, March 12, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Wed, Jun 10, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;