Background
What is the difference between a statement and expression
Specific to JavaScript:
What is the difference between an expression and a statement in JS?
JavaScript: declarations vs expressions vs statements
return
expects an expression as the argument. if statements are not expressions (makes sense, since statement is in the name).
The implementation details of JSX (that stuff with <Tags>
, but in javascript) is also relevant. JSX is compiled into normal JavaScript.
<MyButton color="blue" shadowSize={2}>
Click Me
</MyButton>
compiles to
React.createElement(
MyButton,
{color: 'blue', shadowSize: 2},
'Click Me'
)
documentation.
If you want to evaluate a JavaScript expression in JSX you need to enclose it in curly braces.
const myButtonColor = 'blue'
//...
<MyButton color={myButtonColor} shadowSize={2}>
Click Me
</MyButton>
Back to the Question
Ways of accomplishing if-like functionality:
- inline logical and (
&&
)
- ternary operator (
?
)
return
in if/else statements
Let's look at some examples:
Inline Logical And
render() {
return (
<View>
{this.state.error && <Text> There's an error! </Text>}
</View>
)
}
This method is the simplest and I recommend trying it first. It makes sense when you don't want to do anything if the condition evaluates to false. &&
behaves a bit different in javascript than in other languages. When this.state.error
evaluates to false, render returns this.state.error, which may have unintended consequences if this.state.error
happens to be the empty string or 0
.
Ternary Operator
render() {
return (
<View>
{this.state.error ? <Text>Error!</Text> : <Text>No Error!</Text>}
</View>
)
}
The biggest problem with this is that the lines get long pretty quickly. You can get around this with parentheses.
render() {
return (
<View>
{this.state.error ? (
<Text>Long, detailed error message</Text>
) : (
<Text>No Error!</Text>
)}
</View>
)
}
You could alternatively use JavaScript strings declared before return along with this method.
Return in if Block
render() {
if(this.state.error) {
return (<Text>Long, detailed error message</Text>)
}
else {
return (<Text>No Error!</Text>)
}
}
The problem with this method is if that if you have a long render method and a small conditional change, you will have to nearly repeat the render function in each if block. I generally use this method as a last resort.