In this post I will discuss how you can use conditional rendering in your React.js projects.
You can conditionally render jsx elements by using two methods.
1. { condition && jsx elements }
{ condition ? jsx element : other jsx element }
It may seem trivial at first, but it forms the crux of react development as you will be using this stuff a lot in your projects.
Ok lets learn them.
1. { condition && jsx elements }
I use this one when there is no element/data in the screen to display to the user.
For example,
When the user first enters your website and wants to add some data into it, we can use this conditional rendering code to say that "you have no entries" or "you have no data entered" or something like that.
return(
<div>
{ !data && <div> You have entries </div>}
<input type="text" placeholder="Write something" value={input_variable}></input>
</div>
After the user enters a data, the conditional will not render anything as the condition is now false.
Powerful yet simple concept in React.
You can use this concept in a lot of ways here but, I use this conditional for this purpose.
If you use some different logic, please mention it in the comments.
2. { condition ? jsx element : other jsx element }
This one is a more advanced one to grasp but is super useful in many use cases.
This conditional can be treated as a super set of the first one mentioned in this post.( Mathematicians will know this concept very well)
The first conditional rendering concept just displays only one jsx element if it is true.
The second one will help you display either one of the two elements you try to display with a conditional.
If you did not understand any of the above I will explain with an example.
So if you want to render an error message if the user input is wrong and in turn if the user input is correct and want to render the input value, you can use this conditional rendering concept.
<div>
<input type="text" placeholder="Write something" value={input_variable}></input>
{!error ? <div>The input data the user entered {inputdata}</div> : <div>{error_message}</div>}
</div>
When I first started learning this conditional rendering concept in react, It was extremely difficult to understand what is going on.
But consistent reading of many articles about this topic and watching YouTube and Udemy videos made me grasp this conditional rendering stuff and now I know how to use it in my projects.
If you are struggling with it, you can save this post and read it again and again to get hold of it.
And that's how you use conditional rendering in your projects.
If you have any doubts please ask in the comments and I will try to solve them.
Thank you for reading!!
Check out my portfolio: Gautham's portfolio
Check out my blog: coding-magnified.tech
If you want to appreciate my or support me, you can buy me a coffee with the link below,
Top comments (0)