How to concatenate two JSX fragment or variables or string and component (in Reactjs)?
Use arrays:
let lineComponent = <Line key={line.client_id} line={line}/>;
if (line.created_at) {
return [
<div key="date" className="date-line"><strong>{line.created_at}</strong></div>,
lineComponent,
];
} else {
return chat_line;
}
Or use fragments:
import createFragment from "react-addons-create-fragment";
let lineComponent = <Line key={line.client_id} line={line}/>;
if (line.created_at) {
return createFragment({
date: <div className="date-line"><strong>{line.created_at}</strong></div>,
lineComponent: lineComponent,
});
} else {
return chat_line;
}
In both cases, you have to provide keys for React. In case of array, you set key directly on element. Regarding fragments, you provide key:element pairs.
NOTE:
When returning from render
method, you can only return single element, or NULL
. Examples provided are invalid in that case.
For React Native, I prefer this technique:
- pro: in contrast to the array technique you don't have to artificially create keys
- con: requires the overhead of a containing element (e.g., View, below)
jsx = <Text>first</Text>;
jsx = <View>{jsx}<Text>second</Text></View>;
You can use empty tags, I mean, <>
and </>
, whenever you just don't want any additional Container-Element
(e.g. <View>
), like below:
render() {
return (
<>
<Text>First</Text>
<Text>Second</Text>
</>
);
}
Example:
import React from 'react'
import { View, Text } from 'react-native'
import Reinput from 'reinput'
export default class ReinputWithHeader extends Reinput {
constructor(props) {
super(props);
}
render() {
return (
<>
<View style={{backgroundColor: 'blue', flexDirection: 'row', alignSelf: 'stretch', height: 20}}>
<Text>Blue Header</Text>
</View>
{super.render()}
</>
);
}
}
Note: I tested and it works on
react-native
too; see also Fragments.