Hello I am stuck on this issue where I can't figure out how to do inline if else statment in react native.
{currentSlideIndex == 0 ? (
<>
<KeyboardAvoidingView style={{flex:1}} behavior='position'>
<BlurView intensity={20} tint="light" >
<Text style={styles.label}>Name</Text>
<TextInput
value={name}
onChangeText={onNameChange}
style={styles.input}
/>
</BlurView>
</KeyboardAvoidingView>
</>
):(
<>
<KeyboardAvoidingView style={{flex:1}} behavior='position'>
<BlurView intensity={20} tint="light" >
<Text style={styles.label}>Surname</Text>
<TextInput
value={name}
onChangeText={onNameChange}
style={styles.input}
/>
</BlurView>
</KeyboardAvoidingView>
</>
)}
I want it to make it so that I have currentslideIndex == 0 , currentslideIndex == 1 ,currentslideIndex == 2.
CodePudding user response:
Try this code below:
{
currentSlideIndex == 0 ? (
<>
{/* code for slide 0 */}
</>
) : (currentSlideIndex == 1 ? (
<>
{/* code for slide 1 */}
</>
) : (
<>
{/* code for slide 2 */}
</>
)
)
}
CodePudding user response:
if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.
So in Jsx it actually becomes something like
render(if (true) return 0)
// This doesn't work because you can't put conditional inside function calls
But if you were mapping inside jsx using { x.map(x => { if (true) return <Component //>)}
would work. For Conditionals you can only use ternary.
But You can achieve what you are saying by using Immediately Invoked Function Expression (IIFE)
render() {
return (
<View style={styles.container}>
{(() => {
if (this.state == 'news'){
return (
<Text>data</Text>
)
}
return null;
})()}
</View>
)
}
CodePudding user response:
you want something like:
{currentSlideIndex === 0 ?
(...) :
currentSlideIndex === 1 ?
(...) : //currentSlideIndex === 2
(...)
}
you can actually nest ternaries so that there are multiple if/else if conditions!
OR:
you can have a variable before the return of your render function i.e.
let keyboardAvoidingView;
if (currentSlideIndex === 0) {
keyboardAvoidingView = ...
}
else if (currentSlideIndex === 1) {
keyboardAvoidingView = ...
}
else {
keyboardAvoidingView = ...
}
then in render, just render your variable:
{keyboardAvoidingView}