Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for React Native Conditional Rendering
Vladimir Vovk
Vladimir Vovk

Posted on

     

React Native Conditional Rendering

In general, conditional rendering in React Native is the same as inReact. But be aware, that in React Native we can render strings only inside theText component. So, for example, if we will try to put a string inside aView we will get an error.

Inline if with logical&& operator.

<View>{!!error&&<ErrorMessage/>}</View>
Enter fullscreen modeExit fullscreen mode

☝🏻 Double negation!! operator is very important here (also we can use theBoolean 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 istruthy. And will return the left side of the condition if the left side isfalsy.

Imaging we have a component:

<View>{error&&<ErrorMessage/>}</View>
Enter fullscreen modeExit fullscreen mode

If theerror variable will be anobject,null orundefined 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 aView component.

// error = ''// {error && <something>} will return the error variable,// which equals to the empty string and we will get:<View>  ''</View>// which will throw an error, because we// can't render strings inside a View
Enter fullscreen modeExit fullscreen mode

Inline if-else with ternary? operator.

{error?<ErrorMessage/>:<SuccessMessage/>}
Enter fullscreen modeExit fullscreen mode

or

{error?<ErrorMessage/>:null}
Enter fullscreen modeExit fullscreen mode

Here we can returnnull or<></> (React Fragment) depend on our component structure and return type.

if statement

...constError=()=>{if(!error){returnnull}return<ErrorMessage/>}return(<View><Error/></View>)
Enter fullscreen modeExit fullscreen mode

Code example

Please usethis Expo Snack to see the full code and play with it, press 💖 button and happy hacking! 🎉

Credits

Photo byIsaac Struna onUnsplash.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Heya! 👋 I am passionate about Mobile and Web technologies, React Native, React, building beautiful user experiences, and making the world a better place.
  • Location
    Planet Earth
  • Joined

More fromVladimir Vovk

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp