Reputation: 173
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. Can anyone tell me if i am doing this in the right way. Any help is appreciated. Thank you.
Upvotes: 1
Views: 9924
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
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
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