Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate JSX components in React Native

For example, I wanna show a list of names. So I wanted to do something like this:

var returnValue; for (eachName of _names) {   returnValue += (   <TouchableHighlight     onPress={() => this._onPressButton}>       <Text>       {eachName}       </Text>   </TouchableHighlight>); } return returnValue; 

However, that is not valid. Which brings me to my question: How do I concatenate a dynamic amount of JSX components in React Native.

like image 307
Isaac Paul Avatar asked Apr 30 '15 14:04

Isaac Paul


People also ask

How do you concatenate in JSX?

To concatenate JSX elements into an array in React: Initialize an empty array. Use the push() method to push JSX elements into the array. Set the key prop on the outermost JSX element to a unique value.

How do you concatenate in react native?

Use the + operator to concatenate two string variables in React Native: const helloWorld = hello + world; Another version with a hardcoded string: const helloWorld2 = hello + 'World!

How do you concatenate props in React?

Use a template literal to concatenate a string in React props, e.g. <div className={ border ${myClass} }> . Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.

What is JSX element []?

What is JSX? JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.


2 Answers

Figures I figure it out soon as I ask stackoverflow. The code needs to be put into an array:

var returnValue = []; for (var i = 0; i < _names.length; i++) {    returnValue.push(   <TouchableHighlight onPress={() => this._onPressButton}>       <Text>       {_names[i]}       </Text>   </TouchableHighlight>); } return returnValue; 

There is also more information here: http://facebook.github.io/react/docs/multiple-components.html#dynamic-children

like image 111
Isaac Paul Avatar answered Oct 16 '22 11:10

Isaac Paul


Maybe a more elegant way:

return <View> {_names.map((eachName) => {   return (     <TouchableHighlight onPress={() => this._onPressButton}>       <Text>       {eachName}       </Text>     </TouchableHighlight>   ); })} </View> 
like image 25
Yinfeng Avatar answered Oct 16 '22 10:10

Yinfeng