How to combine two JSX fragments or variables or a string and component (in Reactjs)?

I know that JSX can be very misleading because it looks like strings, and it doesnโ€™t, so the term โ€œstringโ€ is in question, even if we donโ€™t actually manipulate strings.

Here is a sample code (wrong, obviously):

let line = <Line key={line.client_id} line={line}/>; if(line.created_at) { return <div className="date-line"><strong>{line.created_at}</strong></div> + line; } else { return chat_line; } 

I have a string, and I want to "concatenate" some divs in front of it under certain conditions. What will be the correct syntax? I tried brackets, brackets, plus a sign ... None of them seem to work ...

thanks

+25
concatenation reactjs jsx
source share
4 answers

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 snippets:

 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 must provide the keys for React . In the case of an array, you set the key directly on the element. As for fragments, you provide key pairs: element.

Note: When returning from the render method, you can return only one element or NULL . The examples given are not valid in this case.

+44
source share

For React Native, I prefer this technique:

  • pro: unlike an array method you don't need to artificially create keys
  • con: requires the overhead of the containing element (e.g. View below)
 jsx = <Text>first</Text>; jsx = <View>{jsx}<Text>second</Text></View>; 
+10
source share

You can use empty tags, I mean, <> and </> when you just don't want any additional Container-Element (like <View> ), as shown 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 checked and it works on react-native too; see also fragments .

Preview:

enter image description here

+2
source share

If you agree to using a parent object, such as another div, you can also do it like this:

 let line = <Line key={line.client_id} line={line}/>; if(line.created_at) { return <div><div className="date-line"><strong>{line.created_at}</strong></div>{line}</div>; } else { return chat_line; } 
+1
source share

All Articles