How to concatenate JSX components in React Native

React NativeReact Jsx

React Native Problem Overview


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.

React Native Solutions


Solution 1 - React Native

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

Solution 2 - React Native

Maybe a more elegant way:

return <View>
{_names.map((eachName) => {
  return (
    <TouchableHighlight onPress={() => this._onPressButton}>
      <Text>
      {eachName}
      </Text>
    </TouchableHighlight>
  );
})}
</View>

Solution 3 - React Native

let returnValue = _names.map(eachName =>
 <TouchableHighlight
    onPress={() => this._onPressButton}>
      <Text>
      {eachName}
      </Text>
  </TouchableHighlight>);
return returnValue;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIsaac PaulView Question on Stackoverflow
Solution 1 - React NativeIsaac PaulView Answer on Stackoverflow
Solution 2 - React NativeYinfengView Answer on Stackoverflow
Solution 3 - React Native象嘉道View Answer on Stackoverflow