By user8026867


2017-05-18 11:05:54 8 Comments

I need to change render function and run some sub render function when a specific state given,

For example:

render() {
    return (   
        <View style={styles.container}>
            if (this.state == 'news'){
                return (
                    <Text>data</Text>
                )
            }
        </View>
    )
}

How can I implement that without changing scenes, I will use tabs to change content dynamically.

9 comments

@Viraj Singh 2019-05-22 13:35:31

What about switch case instead of if-else

  render() {
    switch (this.state.route) {
      case 'loginRoute':
        return (
            <Login changeRoute={this.changeRoute}
              changeName={this.changeName}
              changeRole={this.changeRole} />
        );
      case 'adminRoute':
        return (
            <DashboardAdmin
              role={this.state.role}
              name={this.state.name}
              changeRoute={this.changeRoute}
            />
        );
    }

@sneha 2019-04-25 09:29:37

For this we can use ternary operator or if there is only one condition then "&&" operator .Like this:- //This is for if else

render() {

return (   
    <View style={styles.container}>
      {this.state == 'news') ?
           <Text>data</Text>
        : null}
    </View>
)

}

//This is only for if or only for one condition

render() {

return (   
    <View style={styles.container}>
      {this.state == 'news') &&
           <Text>data</Text>
        }
    </View>
)

}

@Manish 2018-08-20 11:19:23

I do like this and its working fine.

constructor() {
   super();

   this.state ={
     status:true
   }
}

render() {
   return( 

     { this.state.status === true ?
           <TouchableHighlight onPress={()=>this.hideView()}>
             <View style={styles.optionView}>
               <Text>Ok Fine :)</Text>
             </View>
          </TouchableHighlight>
           :
           <Text>Ok Fine.</Text>
     }
  );
}

hideView(){
  this.setState({
    home:!this.state.status
  });
}

@Manish 2018-08-21 08:12:21

@Pierre.Vriens Instead of if-else, you can use ternary operators in render() method. Syntax :- condition ? expr1 : expr2 Ex. if (this.state.status === true) { } else { }

@Brynner Ferreira 2018-10-08 20:47:29

Perfect, thanks!

@Chase Sandmann 2018-09-27 20:16:47

There's a Babel plugin that allows you to write conditional statements inside JSX without needing to escape them with JavaScript or write a wrapper class. It's called JSX Control Statements:

<View style={styles.container}>
  <If condition={ this.state == 'news' }>
    <Text>data</Text>
  </If>
</View>

It takes a bit of setting up depending on your Babel configuration, but you don't have to import anything and it has all the advantages of conditional rendering without leaving JSX which leaves your code looking very clean.

@Mayank Shukla 2017-05-18 11:12:47

As per DOC:

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

Basic Rule:

JSX is fundamentally syntactic sugar. After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects. We can embed any JavaScript expression in JSX by wrapping it in curly braces.

But only expressions not statements, means directly we can not put any statement (if-else/switch/for) inside JSX.


If you want to render the element conditionally then use ternary operator, like this:

render() {
    return (   
        <View style={styles.container}>
            {this.state.value == 'news'? <Text>data</Text>: null }
        </View>
    )
}

Another option is, call a function from jsx and put all the if-else logic inside that, like this:

renderElement(){
   if(this.state.value == 'news')
      return <Text>data</Text>;
   return null;
}

render() {
    return (   
        <View style={styles.container}>
            { this.renderElement() }
        </View>
    )
}

@user8026867 2017-05-18 11:15:12

can I do like that? render() { return ( <View style={styles.container}> if (this.state == 'news'){ return ( <Text>data</Text> ) }

@user8026867 2017-05-18 11:15:31

so return inside return is possible? or two different returns in same render function scene I need to change sub content of return

@Mayank Shukla 2017-05-18 11:17:52

yes that is possible but, in a different way directly we can't use if/else inside JSX so use ternary operator for conditions, use this: render() { return ( <View style={styles.container}> {this.state == 'news' ? <Text>data</Text> : null } </View> ) }

@user8026867 2017-05-18 11:30:40

` <Text style={styles.instructions}> { if (this.state.page == 'sohbet'){ } ` not possible? } </Text>

@Mayank Shukla 2017-05-18 11:34:20

that is well explained in doc, check this for reason: reactjs.cn/react/tips/if-else-in-JSX.html

@user8026867 2017-05-18 11:40:33

404 but how can I call a function rather than a text in here this.state.page == 'sohbet' ? <Text>data</Text> :null

@Mayank Shukla 2017-05-18 11:44:16

it was working don't know what's the issue,reason is: The content of {...} must be an expression, if-else/for/switch are statements. yes you can do one thing you can call a function and put the if/else inside that, will update the answer :)

@Mayank Shukla 2017-05-18 11:47:04

check the updated answer how to call a function.

@user8026867 2017-05-18 11:51:33

..return <Text>{res.text()}</Text>... that function returns this but it show nothing is that wrong I nee to return jsx code from this function

@Mayank Shukla 2017-05-18 11:54:51

what is res.text() ? if test is a name of function then you need to call that by using this.text(), not by res can you show the full code it will be easy to help you, check the updated answer how to call the function.

@user8026867 2017-05-18 11:57:06

its just text //alert(res.text()); works but not returning anything to text inside

@user8026867 2017-05-18 12:02:55

pulldata() { return <Text>aaa</Text> // send http request in a new thread (using native code) RNFetchBlob.fetch('GET', 'bigpaaasasas', { // Authorization : 'Bearer access-token...', // more headers .. }) // when response status code is 200 .then((res) => { // the conversion is done in native code // let base64Str = res.base64() //alert(res.text()); // this.state = {page: res.text()}; return <Text>aaa</Text>

@Mayank Shukla 2017-05-18 13:08:11

its a asyn call it will not return the updated div directly, you need to use the state variable, like this: pulldata() { RNFetchBlob.fetch('GET', 'bigpaaasasas';, { Authorization : 'Bearer access-token...', }) .then((res) => { let base64Str = res.base64() this.setState({page: res.text()}); }) } render() { return ( <View style={styles.container}> <Text>{this.state.page == 'news' ? : this.state.page : 'aaa'</Text> </View> ) }

@Mayank Shukla 2017-05-18 13:09:08

set the data in state variable and once you do setState it will update the ui, and check the condition inside render method.

@sooper 2017-05-18 13:35:32

I find this way is the nicest:

{this.state.yourVariable === 'news' && <Text>{data}<Text/>}

@MMachinegun 2017-10-23 16:22:13

I agree, this is the nicest of the bunch. Returning null with a ternary-operator is unnecessary ;)

@sumit kumar pradhan 2018-11-05 02:11:07

@Fatih Aktaş 2019-01-14 22:36:25

This should be added to the main answer.

@Diego Mello 2017-05-18 18:14:49

Usually, I do this:

_renderNews () {
  if (this.state.page === 'news') {
    return <Text>{data}</Text>
  }
  return null
}

render () {
  return (
    <View>{this._renderNews}</View>
  )
}

@mariusz 2018-10-09 15:25:29

This is an anti-pattern. _renderNews should be a stateless component if you need to move logic out of render.

@Jagjot Singh 2017-05-18 11:08:03

You can do this. Just don't forget to put "return" before your JSX component.

Example:

render() {
    if(this.state.page === 'news') {
        return <Text>This is news page</Text>;
    } else {
        return <Text>This is another page</Text>;
    }
}

Example to fetch data from internet:

import React, { Component } from 'react';
import {
    View,
    Text
} from 'react-native';

export default class Test extends Component {
    constructor(props) {
        super(props);

        this.state = {
            bodyText: ''
        }
    }

    fetchData() {
        fetch('https://example.com').then((resp) => {
            this.setState({
                bodyText: resp._bodyText
            });
        });
    }

    componentDidMount() {
        this.fetchData();
    }

    render() {
        return <View style={{ flex: 1 }}>
            <Text>{this.state.bodyText}</Text>
        </View>
    }
}

@user8026867 2017-05-18 11:09:37

can you show me a little full working example sorry I am new to this

@Jagjot Singh 2017-05-18 11:42:37

@user8026867 example added

@user8026867 2017-05-18 12:18:57

i want to return from inside a function

@Jagjot Singh 2017-05-18 12:35:48

@user8026867 you can make a function and return the JSX component there. Try it and see if you can make it otherwise I'll give you an example.

@user8026867 2017-05-18 12:36:52

alert works ok but not rendering happens after .then how can I do that pulldata() { RNFetchBlob.fetch('GET', 'bigcom', { }) .then((res) => { alert(res.text()); return <Text>{res.text()}</Text> }) .catch((errorMessage, statusCode) => { alert(errorMessage); }) }

@Jagjot Singh 2017-05-18 17:07:06

@user8026867 You shouldn't fetch data like this. I've added an example on how to fetch data from the internet and show it in your render method. You should use states wherever you want your data to be dynamic. And moreover do not call functions in the render method as render method keeps re-rendering multiple times, which may result in calling the same function multiple times unnecessarily. I hope this helps

@user8026867 2017-05-18 17:43:30

{ this.state.page == 'haberler' ? this.pulldata(); return <Text>{this.state.bodyTexts}</Text> :null }

@Shubham Khatri 2017-05-18 11:39:44

You can't provide if-else condition in the return block, make use of ternary block, also this.state will be an object, you shouldn't be comparing it with a value, see which state value you want to check, also return returns only one element, make sure to wrap them in a View

render() {
    return (
      <View style={styles.container}>
      {this.state.page === 'news'? <Text>data</Text>: null}
      </View>

     )
}

@user8026867 2017-05-18 12:17:11

what is div.....

@Shubham Khatri 2017-05-18 12:22:36

My mistake, didn't see the react-native tag, it should be View and not div

@user8026867 2017-05-18 12:32:01

btw I need to return text after RNFetchBlob function

@user8026867 2017-05-18 12:33:12

pulldata() { RNFetchBlob.fetch('GET', 'bigdsas', { }) .then((res) => { alert(res.text()); return <Text>aaaf</Text> }) .catch((errorMessage, statusCode) => { alert(errorMessage); }) return <Text>iop</Text> }

Related Questions

Sponsored Content

43 Answered Questions

[SOLVED] JavaScript closure inside loops – simple practical example

7 Answered Questions

[SOLVED] Ukkonen's suffix tree algorithm in plain English

52 Answered Questions

[SOLVED] Loop inside React JSX

  • 2014-04-05 05:29:28
  • Ben Roberts
  • 663513 View
  • 976 Score
  • 52 Answer
  • Tags:   javascript reactjs

16 Answered Questions

[SOLVED] Can you force a React component to rerender without calling setState?

  • 2015-06-03 16:44:58
  • Philip Walton
  • 616625 View
  • 515 Score
  • 16 Answer
  • Tags:   reactjs react-jsx

8 Answered Questions

[SOLVED] Why use Redux over Facebook Flux?

4 Answered Questions

[SOLVED] Custom navigation with Navigator component in React-Native

10 Answered Questions

[SOLVED] How to access the correct `this` inside a callback?

17 Answered Questions

[SOLVED] How to decide when to use Node.js?

13 Answered Questions

[SOLVED] React "after render" code?

  • 2014-10-24 21:19:36
  • Oscar Godson
  • 221255 View
  • 296 Score
  • 13 Answer
  • Tags:   javascript reactjs

1 Answered Questions

[SOLVED] How to update state of reactjs app by building on existing state?

Sponsored Content