Stop Conditional Rendering in React Without Knowing This (&& vs Ternary Operator)
HTML-код
- Опубликовано: 2 июн 2024
- 👉 NEW React & Next.js Course: bytegrad.com/courses/professi...
Hi, I'm Wesley. I'm a brand ambassador for Kinde (paid sponsorship).
👉 Add authentication to your app FAST: bit.ly/3QOe1Bh
👉 NEW React & Next.js Course: bytegrad.com/courses/professi...
👉 Professional JavaScript Course: bytegrad.com/courses/professi...
👉 Professional CSS Course: bytegrad.com/courses/professi...
👉 Discord: all my courses have a private Discord where I actively participate
🔔 Email newsletter (BIG update soon): email.bytegrad.com
⏱️ Timestamps:
0:00 Ternary operator
0:42 && operator
1:08 Beginner mistake
2:13 Solution 1
2:28 Better solution
3:03 Best solution
3:28 Junior mistake
3:50 Important!
#webdevelopment #programming #coding
My Professional React & Next.js course is OUT NOW now! Find it here: bytegrad.com/courses/professional-react-nextjs -- this is the #1 resource to master the latest React & Next.js, my absolute best work.
Ternary operators are great if you're only dealing with one or two lines, but when they're used to conditionalize big blocks of output they immediately become really hard to read. I avoid nested ternary for the same reason. Good code isn't just bug free and performant, it is maintainable and extensible as well.
I saw such code with two or even three nested ternar operators, it's really ugly and hard to read, double ! it's a way more easier to read.
I 100% agree. It's almost always better to break the code up into smaller components and use an early return inside of an if statement
As a lead dev, I recommend creating derived variables like hasProducts that handles the logic (ie products.length > 0) so that you're not cluttering up your render. I'd also recommend limiting the usage of ternarys. And if you're nesting them, it may be time to factor your component.
Good tips, thanks for sharing
could you expand your point (for a beginner like me) , please? do you mean creating a boolean variable `const hasProducts = true` if products.length > 0 ? and then use it in the conditional rendering? . Thanks in advance
OP recommends creating a variable like const hasProducts = Boolean(list.length). The idea is you avoid both, printing a 0 om screen and cluttering the jsx with extra logic
I've just recently come across your channel and I love the content that you create. The explanations are straight-to-the-point and easy to understand, and the topics are practical and useful. Thanks very much!
Appreciate it, that’s exactly my goal. Thanks 😊
Wow. Your way of presentation and teaching is so much better. You make us aware about the possible problem that could occur and how to fix. Watched your clsx video too and it was awesome.
Thanks for making these videos. Keep making these.
Thanks, will do 😃
Using the && operator is just harder to read for me, glad I avoided it, never have to worry about these edge cases.
For better readability of conditionals, you can add something like Show wrapper component:
function Show({ when, fallback = null, children }) {
return when ? children : fallback
}
it will also solve the problem of having to convert to boolean, since you always have a ternary with default null as 'else' part
Products in stock
Interesting point
The definition of unnecessary complexity.
Awesome insight! Any way to have a warning with eslint, when you are using && with a value that could be 0 or NaN?
Good idea
Another approach is to use ifs and early-return style to explicitly render null. I think it's much easier to read than either of the approaches shown in your video.
Beginning of my career, I had a lot of random 0s pop up around the apps 😂 When I found this out I made a pretty big pull request fixing all these issues...
Haha yeah it happens
Every video I watch from you I find myself doing such mistakes in my code without ever realizing it 😂
i prefer to use 'smth ?? fallback' instead of 'smth ? fallback : null' which does the same thing, but much shorter
This wouldn’t work in the case of the array.length
The ?? Operator only checks for null and undefined values so if array.length returns 0, the operator wouldn’t be able to catch that
This has to do with truthy and falsely. Stupid how JavaScript works. I don’t like ternaries in my JSX. It obfuscated so much. I always try to use an early return.
Yep, it’s JSX not JS. I agree, ternaries clutter up JSX too much
@ByteGrad Yeah but everything within {} is evaluated as Javascript. Didn't mean to bite down. I like your content. I learned some new hooks from your channel.
True but if you put undefined, null, empty string etc in the curly braces JSX won’t output that on the page, however it will output 0 and NaN. That’s confusing
Edit: no problem mate
Hi Wesley, your nextjs course isn't available yet? i've already taken your javascript course, your Nextjs cour isn't available yet? i've already taken your javascript course. Thanks !
Hi, it’s almost finished. Make sure you’re on the email list :)
looks like i just found a promising channel. like your vid mate
Awesome, thank you!
I'm pretty sure that in the first case it has nothing to do with JSX. It simply converts the 0 to a string "0" and outputs that. Many developers thing that (0 && 1) will return false, but && will short-circuit to the first falsey value (in this case 0), not false:
{0&&1}
{0}
0
Edit: i fucked up the closing tags, that's what i get for commenting code on a phone
Can u elaborate? I still don't get what 0 && 1 means. It won't give a bool?
@@anonymoussloth6687 no it won't. *&&* will return the first value if it's truthy, else the second value. So a && b should be equivalent to something like a ? a : b
However, what JSX does is it omits null, undefined, etc. from the render. So, if in a && b a is truthy and b is undefined, && will evaluate to undefined, but JSX will render this undefined as an "" rather than "undefined". This is useful, yes, but not very consistent and can be misleading for new devs, hence why you shouldn't rely on implicity
@@y7o4ka oh. But then ur saying in js, if there is a if state like if(a && b) this doesn't give a bool, it gives either a or b depending on their truthy-ness? Suppose a was falsy, it wouldn't give false but rather the value of a itself?
@@anonymoussloth6687 Exactly. Open a browser console or launch node and enter something like `"truthy" && "hello!"` or `undefined && "bye :("`. You should see "truthy" and then `undefined`. Then `if` will see whatever && evaluated to.
So if("truthy" && "hello!") will evaluate to if("hello!"). If will see that "hello!" is truthy and enter the block
Awesomely explained, keep up the good work!
I really dislike the ternary returning null if false, it delays the understanding of what is happening when you read the code. With && you already know that this will only be displayed if the condition is true.
As for the condition, I personally prefer explicit conditions like array.length > 0, even though !!array.length is something quite common, it's just faster for the brain to process array.length > 0 as it is closer to the reality
Clearly the most valuable comment ! Explicit condition is usefull for maintanability and readability
@@monome9992 I totally agree. The more explicit, the better. Using `!!` is kinda tricky and could trip up someone.
true, even though I know what !! does it still takes time to figure it out so length > 0 is easy to process
what about the ?? operator does it not help?
Awesome video +++++++++++++ 🙂
Awesome man
Do you have any plan for react course???
Yes, it’s almost finished. Make sure you’re on the email list :)
can we conditionally render using signals?
great video!
Thanks!
That's why I use !! to transform the thing in a boolean then I do the && and avoid the ternary.
It happened to me xd, thanks for the tip
imo the cleanest way to handle this would be to use null coalesce (??)
If there was a way to smash the like button for this video a thousand times, I would have done it
Haha appreciate it
Thanks man
Ternaries in JSX are way overused. I prefer to break it down into a smaller component and use an early return inside of an if statement. Yes it creates more lines of code but the added readability is worth it
I was struggling to understand and find these types of good practices. Your videos are a blessing. Can i suggest some topics i find hard to capture? myb you can share your insight
Good to hear. Yes let me know
@@ByteGrad thanks. On top of my head
Code splitting in nextjs,
how to optimize render for different vw,
When should we must use styles instead of tailwind class.i heard dynamic rendering still has bug with tailwind classes
Good ideas, thanks
Cant we use {productsInStock && "Products in stock"} ?
An empty array is truthy. So if the array is empty we would then show "Products in stock".
@@ByteGrad ahh intresting, thanks for insight!
man that 0 value in jsx f*ck me up so many times.
in web this will render 0 as you say but in react native it crash the app so its kind of a big deal to do this correct
Great point
You can increase your voice little bit, because I need to keep full volume in my Mac
Thanks, will do. Didn’t realize volume was so low
Thnk
Here's what I used to do for rendering with condition
{!condition || return}
Mr. Clenched Jaw
i usually just negate or double negate the condition just to be sure
JSX does not define how logical operators work-this is pure JavaScript due to it being able to use non-boolean values as conditionals. JSX just considers null, undefined and false as "holes" in the JSX tree. The reason this doesn't apply for strings, and numbers (incl. NaN) is because otherwise you couldn't render those in normal circumstances.
(I'm starting writing this comment with start of the video)
And that's why I don't like loosely-type langs. I was love them, as a beginner. You can do so much 'smart' code that will abuse truthy and falsy values.
If you need to use non boolean, you can Bang Bang in front or it, or convert it in less hipster way to boolean, but after all you should face logic for boolean only with booleans!
I got dev fellow that whas always doing `if(myVar === undefined) doThis(); if(myVar === null) doThat(); if(myVar === 0) doThose()` just to protect himself from those scenarios.
Binary world is way simpler, we don't need quantum physics with alternate timelines to compose whole universe from here's and now's.
Good take though. Many people and developers (yes this days, not all dev's are people 🙀) are not aware of it. No one is starting from assembly any more?
Good points
Hii😊😊
it does show the "", but it's just empty string... so it shows... an empty string
Good point
Plot twist: !!list.length && …
Why not use "??"
1:42 "This is not actually a JavaScript issue, it's actually a JSX issue" - Actually, that's incorrect. This is purely a Javascript behavior. Unlike other languages where && and || return booleans, in Javascript && returns either the first falsy variable, and if none are found, the last truthy variable. || returns either the first truthy variable, and if none are found, the last falsy variable. 0 is falsey, so that's why it returns 0 and it is therefore outputted to the page.
I always don't like conditional rendering, not elegant
is this me or his videos are helpful but hell lot boring
It's just you, it's boring to only you
I saw the thumbnail, didnt even bother to watch the video. And operator is better when u want to return null if the condition isnt met. Period!