i 4322946
i 4322946

Reputation: 173

if...else condition in React Native

i am new to react native. In my application i am stuck with if..else condition in which i am displaying views based on a condition. Here is the code.

if ({ this.state.isSignUp }) {
     <Text> Sign Up </Text>
} else {
     <Text> Forgot Password </Text>
}

In my login page i have links for Forgot password and Sign Up pages for which i am showing a Modal page based on isSignUp bool value. I am jus trying to display a text in the Modal page based on the condition, but i am stuck with the below error.enter image description here Can anyone tell me if i am doing this in the right way. Any help is appreciated. Thank you.

Upvotes: 1

Views: 9924

Answers (3)

hakki
hakki

Reputation: 6511

There is no need to a function in JSX to use conditions.

You can use Inline If with Logical && Operator

It also called ternary operator. For further info please see

Example from React Doc;

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
    </div>
  );
}

--

It can also be used for larger expressions although it is less obvious what’s going on:

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn ? (
        <LogoutButton onClick={this.handleLogoutClick} />
      ) : (
        <LoginButton onClick={this.handleLoginClick} />
      )}
    </div>
  );
}

Upvotes: 0

Tim
Tim

Reputation: 10709

For conditional rendering i would recommend to create a new function. Inside a function you can use if/else like normal. e.g

renderConditionalText() {
    if (this.state.isSignUp) {
        return <Text> Sign Up </Text>;
    }
     return <Text> Forgot Password </Text>; 
}

Upvotes: 3

Anshul Kai
Anshul Kai

Reputation: 4088

Try something like this.

  let text;
  if (this.state.isSignUp) {
       text = <Text> Sign Up </Text>
  } else {
       text = <Text> Forgot Password </Text>
  }
  return text;

Upvotes: 1

Related Questions