Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine child nodes with JSX?

I want to build up a ul list from li elements, but the li elements will come from different sources, so I can't do it in one statement. It appears that JSX can't handle a set of child elements, this gives me a syntax error:

var items = <li>S</li>
  <li>S</li>
  <li>S</li>;

Ideally I want to do something like:

var items1 = <li>S</li>
  <li>S</li>
  <li>S</li>;
var items2 = <li>S</li>
  <li>S</li>
  <li>S</li>;
var list = <ul>{items1}{items2}</ul>;

Is there another way to achieve this?

like image 827
Chris Avatar asked Jan 31 '14 18:01

Chris


People also ask

How do you get child nodes in React?

children should either be a ReactElement or an array of ReactElement, but not components. To get the DOM nodes of the children elements, you need to clone them and assign them a new ref. You can then access the child components via this. refs[childIdx] , and retrieve their DOM nodes via ReactDOM.

Can we use loop inside JSX?

We can build a loop and add a JSX element to an array using the for a loop. elements.


1 Answers

JSX desugars very straightforwardly to Javascript syntax so you can mix it freely.

/** @jsx React.DOM */
var items1 = [ <li>S</li>,            var items1 = [ React.DOM.li({}, "S"),
               <li>S</li>,                           React.DOM.li({}, "S"),
               <li>S</li> ];                         React.DOM.li({}, "S") ];
var items2 = [ <li>S</li>,            var items2 = [ React.DOM.li({}, "S"),
               <li>S</li>,                           React.DOM.li({}, "S"),
               <li>S</li> ];                         React.DOM.li({}, "S") ];
var list = <ul>{items1+items2}</ul>;  var list = React.DOM.ul({}, items1+items2);
like image 174
J. Abrahamson Avatar answered Sep 27 '22 23:09

J. Abrahamson