Sinan Samet Sinan Samet - 26 days ago 15
React JSX Question

Can't add multiple lines of components into variable

I want to save the content in a variable depending on the result of an if statement. But when I add multiple lines it doesn't work.

let content = null
if(this.props.group.name != null){
content = <Text>Just this line works</Text>
<Text>This doesn't work</Text>
}


I can't find out what to do. I can't add + at the end of the line like in Javascript.

Answer

Components need to be wrapped in a parent containing component, unless you create it as an array with keys.

// this would work because it's wrapped inside parentheses and has a parent component
content = (
          <View>
            <Text>Just this line works</Text>
            <Text>This doesn't work</Text>
          </View>
          )

// this works because the components are an array
content = [
           <Text key="1">Just this line works</Text>,
           <Text key="2">This doesn't work</Text>
          ]