Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

like image 522
Nick Heiner Avatar asked Mar 14 '17 16:03

Nick Heiner


2 Answers

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>)
like image 122
Thibaut Remy Avatar answered Oct 01 '22 01:10

Thibaut Remy


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>
like image 44
finalfreq Avatar answered Oct 01 '22 01:10

finalfreq