9 React conditional rendering methods

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this video was brought to you by log rocket the front-end performance monitor that records videos of user sessions along with logs and network data surfacing problems and revealing the root cause of every bug tried today at la rocket comm /yt hey it's Lee Halladay and controlling the flow of your react application is crucial to getting the result that you're looking for here I've got a tweet that I've built and there are a number of things we could change sort of controlling what's displayed for example what if there were no comments we maybe wouldn't show this section at all this show/hide should show or hide the comments and there's nine ways we're going to cover to control whether something is rendered or not so Esteban Adria wrote a great article on the log rocket blog about eight conditional rendering methods he actually touches on more than eight things which is why we're going to cover these nine things that I've entered as Commons into my tweet so we're gonna cover if else how to return null when you don't want to render anything how to store some JX JSX in a variable so that you can control whether something's displayed using that using turn Ares using short-circuit to to decide whether something is displayed or not covering if he's immediately invoked function expressions using sub components to clean up our code and then creating our own if components and then higher-order components to control maybe we only saw show something when the user is authenticated so let's get started I've got the code here that was displaying that tweet we were just looking at it's a very simple creat react app with nothing installed in it except what comes with create react app and just to give a quick overview of what we're looking at we're importing react some CSS that I created to get it to look like this and then we've got a hard-coded array of comments so these are the subjects we're gonna cover over the next ten to fifteen minutes if we come down here we've got sort of the main components that's that's rendering it out this tweet it's inside of a div then we've got the tweet header the tweet body which are this component and this component we're not going to look at those at all where we're gonna focus are the tweet comments so tweet Commons is receiving as a prop this array of comments and we'll just sneak down here to the bottom and this is where we're going to be looking at all these concepts so the first thing we want to cover was it's a symbol if or else statement so imagine we want to control if there's no comments there's no point in showing any of this code at all right so we'll start with an if statement so if comments dot length is zero then we're gonna return one thing so we'll just say no comments sorry else we'll take this whole return statement and place it in the else just like that so I do have comments but let's go back and trick it so let's say let's pass you an empty array of comments so now you can see that it's displaying no comment sorry if we were to come back and pass the comments again we're back so first concept just using if and else to return entire chunks of JSX from a component now let's say we wanted to not say no comment sorry but just to simply have nothing at all well the second concept is you can return null from a component and like null sort of suggests nothing will be rendered so we can do that if we go back and pass our empty array like that now we've got nothing rendered at all now I think oops there we go let's just get back to work cool so I think we can actually clean this code up instead of having it formatted like this the one thing we can do is we can actually get rid of this else statement like that and maybe add an extra space here and I like this approach of sort of I call them guard clauses basically their clauses at the top of your component where you're checking some sort of Clause some conditional and you're just getting out of there as soon as possible so that if you get beyond this if statement you know that in this case we've got comments so we don't have to check for that anymore we've sort of already had the guard Clause at the top and in my opinion it's a little bit cleaner so we've covered how to return null when you want to render nothing the next thing is element variables store JSX in a variable so this is just going to be a quick little example but imagine you're building a form and there could be errors or there might not be errors what you can do is you can create a variable called say error and you can initialize it to no and then if some condition is true let's just say if true in this case because we're just showing how it works we want to set this to something else so let's set it to JSX so we could do a maybe a span with a class name of of error I don't have that set up so let's well why don't we you'll do that quickly just add a dot error we'll set the the color to a nice red there so whenever that happens there was an error please fix cool so let error perfect so error either has null in it or if some condition is true we've put in it some JSX and now we can embed this variable inside of the thing that we're returning from our component so if we come back here we see there was an error please fix if this condition was false for whatever reason then we have nothing being displayed because null error contained null so that's the third way I think it was three anyways yeah is basically you can use a variable that has null or some JSX in it to conditionally render something so that was just an example it doesn't really have too much to do with our tweet example so let's keep going so the fourth way is turn Aries so take your if statements in line so inside of JSX you cannot just embed if statements so you can't say if something it's it's invalid JSX the only sort of way to get that sort of if-else logic inside of your JSX directly is with a ternary so a ternary has two sides to it it's some condition question mark then the truth east side and the falsey side like that so what we're going to do is rigged up our button to show and hide with some states so we can actually click it to show and hide these comments so we'll come up to the top and we will create some state so we'll say whether we want to show it or not and what function to set that show and this will be the use state hook which will begin as why don't we say true cool so turnery we've got our condition verse so we're going to look at the show variable then we have our question mark so if that's true we want to show all of this GSX here and if it's false we will display nothing so we'll put a null I'll hit save and prettier we'll clean up my code and that's the ternary so it's showing right now if I were to set its default value to false it wouldn't show why don't we make it so that the button actually works so on click what we'll do is call set show to be the opposite of whatever it currently is and we can even clean this up with a ternary as well so we'll we'll say if it's show we want to do the opposite when you click the button so that would mean we want to hide and if it's false that would mean we want to show just like that so if we want to hide these show them hide them show them perfect so we used two ternary statements the condition the truth eastside and the false ii side and we also use that just with a string not really with JSX so that's the fourth way the fifth way is sort of a short form version of that when you don't really want to show anything in the false side we can do what's called a short-circuit operator so the way a lot of programming languages worked is if you have a condition to conditions with an end between them so first condition and second condition if the first one is false it won't even try to execute the second one if it is true it will go and execute the second one check the second one and we can sort of use that and the way JavaScript works to basically get rid of the ternary and avoid having to say or null here so we'll say if show and and so this is truthy keep going and because it sort of returns whatever the second half of this conditional is we can get rid of this and this is a short way to show something when it's true so if show and and then the second half of that short-circuit operator and this should still work the same as it did before now there is one caveat with this in that if show happens to be false that's sort of what gets returned from this JSX expression here and in react sort of Dom in the web that's fine but in react native it doesn't like it when you return the false value it sort of freaks out a little bit so I would recommend even though it's a few more characters to just stick with the ternary and be explicit about what your your false on the conditionals returning because that will work in both react Dom and react native the next conditional we are going to look at is the iffy the immediately in in in voted rubes invoked function expression why don't we fix that in voted in a money good time for that invoked so what is that that's basically a way and we're going to be getting rid of this just to show how it works because of the way in JSX you can sort of embed any sort of expression that javascript has there returns a value what we could actually do is invoke or embed a function yes so end of the function end of the expression we're going to wrap the function in parentheses and then call that function immediately so we would need to return from our function and you can already see it's sort of ugly and I wouldn't recommend taking this approach because I I think if you get to this point for whatever reason ternary doesn't work it's probably better to look at another approach that we're going to do where you actually remove all the complexity and move it into a subcomponent but anyways just to show how it works inside of this function it basically gets executed immediately hence the name immediately invoked function expression what we could do is we could say if not show return null and sort of else if it gets here return this so this is another way to conditionally control whether we are showing these comments I'm gonna undo a bunch to basically get us back to where we were before hopefully that's too confusing there we go so we're back to the ternary approach because I prefer it over that if he and the next thing I want to show is using subcomponents when appropriate if you start to add all sorts of conditional logic you can see it starts to sort of get harder to read what's happening and in my opinion it can get cleaned up if we were to basically take this chunk and move it into its own component so I'm going to create a new component here and we'll call it the tweet list we'll say so this receives the comments and we'll do a sort of an Auto returning function and as soon as I fix this code up here to show the tweet list passing in the comments there we go formats the code so you can neat see now it's a little bit easier it's still the same logic the same ternary conditional but if show we render out the tweet list else nothing and now this code is a little bit cleaned up and we have a smaller component here a sub component that is only in charge of rendering out the list it is no logic in it it's just showing the comments that are passed to it just to confirm it's still working we can do that cool so there's a couple other approaches you can take to conditionally showing something the first one I'm gonna show is something that Esteban shows in this article and it's basically an if component and in my opinion reminds me a little bit when you're using something like react router and you've got a path and if the path matches you're gonna show another component so we're gonna create our own sort of mini version of that so what we're gonna do is create a component called if with a big eye there and it's gonna be a functional component so what this is going to receive is basically just one thing well sorry I lied two things the conditional and the children so a child components passed if so what we're going to do is we're going to say if conditional so if the conditional is true let's return the children else or sort of below this if statement we are just going to return null so now we can use this if component right here so we can say if conditional so in our case it's this show variable so if that's true render out the children so we're gonna pass the tweet list as children just like that so it still works and just to explain it a little bit better we've created our own component called if it receives two things a prop called conditional which is a boolean true or false and some children nested inside so this mini component it's only job is basically if the conditional is true to return the children so they get rendered out else or otherwise it's gonna return nothing at all so that's a little way of you prefer this sort of logic you could also go a step further you could almost treat it more like a route component in react rather you could pass in a component to render out like this and make if self-closing so if conditional here's the component to render out so we would come up here then and we would change from children it would be the component and it should function the same cool so now it's very much like a router imagine you have a route with a path say the home path so if that path matches if it's true here's the component to render out anyways that's just a little way you can conditionally show something the last approach we're going to look at is a high order component and that's basically a function that you wrap around another component so you can embed some logic in that higher called high order component that can be reused across sort of multiple other components if that's confusing why don't we actually look at the example so what we're going to do is we're going to create a higher-order component or in other words just a function called with off so it's an arrow function for now so what does this function receive it's going to receive some other component so imagine this entire thing like that so we're going to pass this in and we'll just do a Big C because of the way we want to render it out that you'll see in a second cool and because of the way react works functional components they should they should be functions that you can call right so when we wrap this with auth around another component like we'll do in a second what we want to do is have this higher-order component returned in a sense a component that can be rendered why don't we just look at it because I don't know if I explained it the best so first things first let's wrap this around so with off wrap that whole thing around like that spell it right cool and now we can add some logic in to basically decide are we going to render the component that was passed in to this or are we gonna render something else so what are we gonna check for because we're looking for authentication why don't we just look if there's a user in local storage so local storage if local storage getitem we'll do the user string sort of the user key so if that's true we are going to return a function that will receive props and render out the component that was passed to this higher-order component so these props are the ones that react typically passes to your component when it's called so in our case it's the comments that the tweet comments component is receiving so what we can do is use the spread operator to spread these props out so they get passed in our case to the tweet comments function or component so else and we don't need the else because if the truth part returns we would never get here anyway so I typically avoid the else in that case but we're going to return a span that says you must be authenticated like that okay let's try this out oh boy what did I do alright let's try troubleshoot this what did we pass to with auth we passed this entire you oh I know our higher-order component always has to return a function that can be called so what we missed is that we need to return a function that react will try to render it will try to call there we go so because I have nothing in local storage it's showing this you must be authenticated so we're gonna sneak into the console and we are going to add a key to local storage so set item user it will have a value of Li like that so now if we refresh the page now our with auth higher-order component it checks a local storage it finds that there's a user and it renders the comments just like that it works so if we were to come back and local storage remove item remove that user like that refresh we're back to you must be authenticated cool so now that we've got that done why don't we just rehash what we did with the higher-order component because frankly I find them a little bit confusing but it is an option and the cool thing is we could rap with off around any other component that we want a user to be authenticated in order to see that content so hire a component what it does is it's a function that receives a component and its job is basically to return another function that will be called by react so it'll be rendered so whenever react is trying to render a functional component it calls it and it passes in the props and in our case we're passing those props down to the component that was passed in spreading them out so if we come down and look at how it was used we've wrapped with auth around our tweet comments functional component and it's receiving comments that were passed through props and then spread out so that we can receive them here inside of our tweet comments cool so that was nine ways to conditionally render or control the flow inside of your react application I hope you enjoyed it I hope you learned something take care bye
Info
Channel: LogRocket
Views: 6,057
Rating: undefined out of 5
Keywords:
Id: 9yRCByR3GEM
Channel Id: undefined
Length: 23min 45sec (1425 seconds)
Published: Mon Apr 27 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.