0

I want to execute all lines inside if statement but I can't

this is my code

import React, { Component } from 'react';
import { Text, View } from 'react-native';
class test extends Component {
  constructor() {
    super();
    this.state = { data: [] };
  }
  testFunction = () => {
    return (
      <View>
        <Text>Anything</Text>
      </View>
    );
  };

  render() {
    return (
      <View>{data.length > 0 ? <Text>Hi</Text> : this.testFunction() <Text>Hello</Text>}</View>
    );
  }
}
export default test;

I want to execute (this.testFunction()) and (<Text>Hello</Text>)

thank you

You Nguyen
  • 9,961
  • 4
  • 26
  • 52
Ahmad Abo Zaid
  • 340
  • 1
  • 16
  • please provide your full component codes – You Nguyen Oct 03 '18 at 10:00
  • `import React, { Component } from 'react'; import { Text, View} from 'react-native'; class test extends Component { constructor() { super(); this.state = { data: [], }} testFunction = () => { return ( Anything ) }render() { return ( {data.length > 0 ? Hi : this.testFunction() Hello } );} } export default test;` – Ahmad Abo Zaid Oct 03 '18 at 10:15

2 Answers2

1

You can do that this way:

render() {
  //Is data initialized?
  if (data.length > 0) 
    return (
      <Text>Hi</Text>
    )
  else 
    return (
      {this.testFunction()}
      <Text>Hello</Text>
    )
    
}

But there are better ways. For example, in this way you keep your render function cleaner:

conditionalRender() {
  //Is data initialized?
  if (data.length > 0) 
    return (<Text>Hi</Text>)
  else 
    return (
      {this.testFunction()}
      <Text>Hello</Text>
    )  
}


render() {
  return (
    {this.conditionalRender)}
  )
}
Andriy Klitsuk
  • 564
  • 3
  • 14
0

You can modify your functions such that they return the component.

 condition1 () {
  // do something 
  return ( <FlatList
    data={[{key: 'a'}, {key: 'b'}]}
    renderItem={({item}) => <Text>{item.key}</Text>}
  />);
 }

 condition2 () {
  // do something 
  return ( <Text>Hello</Text>);
 }

And call that in the render

render() {
 return (
  <View> { data.length > 0 ? this.condition1() : this.condition2()} </View>
)}
Chandini
  • 540
  • 2
  • 11