Idiomatic way to append an element in JSX [duplicate]

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:


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 = [

And then pushing whatever you want to the array:


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>

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Found the synthetic property @enterAnimation. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application. Angular4

Similar Posts