ReactJS Tutorial – 16 – Conditional Rendering
- December 25, 2023
- Posted by: MainInstructor
- Category: Go JavaScript React VSCode
![*](https://i0.wp.com/allprowebdesigns.com/wp-content/uploads/2023/12/1703473264_maxresdefault.jpg?resize=840%2C430&ssl=1)
Video Title: ReactJS Tutorial – 16 – Conditional Rendering
When you are building react applications you may often need to show or hide some HTML based on a certain condition luckily conditional rendering in react works the same way conditions work in JavaScript we have four different approaches and we will take a detailed look at each one of them we have
Defaults element variables ternary conditional operator and short-circuit operator let’s begin with the if-else approach I’m going to go back to vs code and first I am going to create a new file called user greeting dot Jas within the file I’m going to create a class component using the react snippet RCE
And I will remove the named export in the JSX I will simply return welcome vishwas in the app component I will include the user breeding component again make sure to import it at the top now if I save the files and take a look at the browser you should be able to see
The message welcome vishwas let’s go back to the user breeding component and make some changes I’m going to begin by adding a constructor with the snippet our Const within the constructor call super and then define the state I am going to create one state property called is logged in and
Initialize it to false in the JSX i am going to add another message that says welcome guests so first let’s add parentheses and an enclosing div tag move welcome vishwas inside the div tag and also add another div tag that says welcome guest now what I want is the message to be
Conditionally rendered based on the East logged in state if I am logged in the message welcome vishwas should be displayed and if I am not logged in the message welcome guests should be displayed let’s see how to achieve that with the first approach that is using the if-else condition in the render
Method let’s add the if-else condition if this dot state dot is logged in so if I am logged in I need to render welcome vishwas so we are going to have a return statement a div tag then welcome vishwas and the else condition that is if it is
Not logged in so else you are going to return hell on disease div tag welcome guests and of course I’m going to comment out the return statement that we had before if I now format the code you can see the if-else rendering if this state is logged in returned
Welcome vishwas else return welcome guest now if we take a look at the browser you can see the message welcome guest is displayed and that is because he’s logged in is set to false if I now change it to true and take a look at the browser you can see that the message
Welcome vishwas is displayed now you might be thinking there’s a lot of repetition and the render method looks crowded can we not simply use the Phils condition on the message being displayed the answer is no default statements don’t work inside the JSX that is because JSX is just syntactic
Sugar for function calls and object construction adding if else statements within the JSX is not valid that is the reason we have if else statements outside the JSX and the entire return statement containing the chair sex is placed inside the if or else block now a better
Approach is the second approach of using element variables in this approach you use JavaScript variables to store elements this will also help you conditionally render the entire component or only a part of the component as well let’s see how I’m going to begin by commenting the if-else blocks
Next I’m going to declare a variable inside the render method let message next we store the appropriate element in this variable based on the condition so if this dot state dot is logged in message is going to be equal to a div tag that contains the text welcome vishwas
Else message is equal to a div tag that contains the text welcome guests and finally we return this message variable in the JSX so return dip tag and within curly braces the variable message if we now save the file and take a look at the browser you can see that
We have the same result welcome Bishwas is displayed change is logged in to false and the message welcome guest is displayed so message is the variable which stores the element to be rendered and hence this is the element variable approach now although this approach looks much better the third approach is even more
Simpler and this approach uses the ternary conditional operator the benefit of this approach is that it can be used inside the JSX so I’m going to comment out what we have done with the second approach and now within the render method I’m going to add the return statement and within
Parentheses we use the conditional operator this dot state dot is logged in question mark a div tag that says welcome Vishwas a colon and then again a div tag which says welcome guest now how does this work the first operator this dot state dot is logged in is evaluated
To either true or false if it is true the second operator is returned in our case the div tag welcome Vishwas if the first operator turns out to be false then the third operator is returned in our case a div tag that says welcome guest I’ve just
Formatted the code and you can see the conditional operator if this dot state dot is logged in is set to true welcome Bishwas is returned if it is false welcome guest is returned now we have is login set to false so if I go back to the browser you should be able
To see the text welcome guest I change it to true and you should be able to see welcome vishwas so this is the ternary conditional operator approach and is probably the approach you might want to follow most of the time keeps the code simple and readable all right the final approach is
The short-circuit operator approach and this approach is just a specific case of this ternary operator approach that we have just learned when you want to render either something or nothing you make use of the short-circuit operator for example right now we return either welcome vishwas or welcome guest based
On the ease logged in value now let’s say if the user is logged in I want to display welcome vishwas and if the user is not logged in I want to render nothing onto the screen so based on is logged in render either welcome vishwas or nothing to do that we simply return
This dot state dot is logged in and % & % div tag welcome vishwas so what happens here is the expression first evaluates the left hand side of the operator this dot state dot is logged in if it is true it also evaluates the right hand side which in our case is the
JSX that will be rendered in the browser however if at all the left hand side evaluates to false the right hand side will never be evaluated as it doesn’t affect the final value of the whole expression and make sure to add the return keyword at the beginning of the statement so
Return this dot state dot is logged in and welcome Bishwas so if is logged in is set to true in the browser we should have welcome Bishwas being displayed and if i change it to false nothing is rendered in the browser so these are the four approaches to conditionally render UI in react
We have defaults element variables conditional ternary operator and the short-circuit operator for most of the cases I recommend you stick to either conditional operator or the short-circuit operator they tend to be much more clean and readable all right in the next video let’s take a look at rendering a list of elements in
React thank you guys for watching feel free to subscribe and I’ll see you guys in the next one
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
thanks
nice tuturial
completed video 16. Thank you 🙂
Thank you
why did we use return <div>{message}</div>, not return {message} ?
Thnx loads…
This stuff cannot be nested. It has to be toplevel inside the return statement.
can we get code snippets for every lecture ?
Is there any difference other than the syntax ?
// Type3: Ternanry Operator
return this.state.isLoggedin ? <div>Welocme Vignesh</div> : <div>Welocme Guest</div>
// Type4: ShortCircuit Condition
return this.state.isLoggedin && <div>Welocme Vignesh</div> || <div>Welocme Guest</div>
thank you so much
reallythanks alot you have excellent way to explaine
please update it usi g functional component ,It's becomes too difficult to understand
in jsx (return) part – can't write if/else
but in render method outside jsx, can write if/else, variable decla&usages, ternary operator, logical &&
– to conditionally render UI in react:
Awesome very good explanation, Thanks
For those who are watching this in 2022 and are unhappy that Vishwas is using classes instead of functions, you can code along using functions. make sure that instead of creating a constructor with this.state={someProperty: "someValue"}, you just create a useState hook like this: const [someProperty, setSomeProperty] = useState("someValue"). Make sure you import {useState} from 'react'. Also whenever Vishwas is using this.setState("anotherValue") to change this.state, you simply uset setSomeProperty("anotherValue") and the state/someProperty changes. And last thing I want to mention is you don't need render (), just return.
Good day wishes
but if else it also works in jsx
I wish that would be more with functions than classes 😀
U are doing grt sir…can you tell me which snippet you are useing for code in react
10:00 Short Circuit Operator double ampersand operator
Thanks for the video. Really helpful
awesome explanation 🙏
return message
This is also enough
Thanks!! Vishwas. I think it's better than paid…
1:33 – IF/ELSE, 5:05 – Element Variables, 7:07 – Ternary Conditional Operator, 9:22 – Short Circuit Operator
How can we return welcome guest with the fourth approach?
After going through so many different paid and unpaid tutorials, I can this one is the best among all.
Thank you .. Good Job
Amazing Video
Why does React don't have directeve like v-if or v-show to conditionaliy render data just like in Vue ???. it is much simpler and easer
im stuck in vanilla javascript… but this makes sense much much more
Love from Bangladesh
You are tutorials so good,why are you not posting in udemy so we can buy from you