i would like to use if
statement in the return of render method , what i mean is something like this :
export default class App extends Component
{
render()
{
return(
<View>
if(this.state.error)
{
<View>
<Image source={{"error"}} />
<Text>An Error Happen</Text>
</View>
}
else
{
<View>
<List dataArray={this.state.items}></List>
</View>
}
</View>
);
}
}
i can use ternary operator , but what i want is to use if
statement if it possible
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>
Ways of accomplishing if-like functionality:
&&
)?
)return
in if/else statementsLet's look at some examples:
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
.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With