In general, conditional rendering in React Native is the same as in React. But be aware that in React Native we can render strings only inside the Text
component. So, for example, if we will try to put a string inside a View
it will throw an error.
Inline if with logical &&
operator.
<View>
{!!error && <ErrorMessage />}
</View>
⚠️ Double negation !!
operator is very important here (also we can use the Boolean
function) because it ensures that the left part of the condition will be a boolean value.
Why it is important? Because logical “and” operator &&
will return the right side of the condition if the left side is truthy
, and will return the left side of the condition if the left side is falsy
.
Imaging we have a component:
<View>
{error && <ErrorMessage />}
</View>
If the error
variable will be an object
/ null
/ undefined
everything will work as expected. But if we will get an empty string for the error ( error = '' ) then our component will brake, because we can’t render strings inside a View
component.
// error = ''
// {error && <something>} will return the error variable (which equals to '')
// and we will get:
<View>
''
</View>
// which will throw an error (can't render strings inside a View )
Inline if-else with ternary ?
operator.
{error ? <ErrorMessage /> : <SuccessMessage />}
or
{error ? <ErrorMessage /> : null}
Here we can return null
or <></>
(React Fragment) depend on our component structure and return type.
if
statement
...
const Error = () => {
if (!error) {
return null
}
return <ErrorMessage />
}
return (
<View>
<Error />
</View>
)
Code example
Please use this Expo Snack to see the full code and play with it.