I'm learning react and I came across the next expression
ReactDOM.render(true && 123 && <functionThatReturnBool> && "foo")
I tried to research a bit, didn't find too many sources, so I played with the code a little bit, and this is what I came up with:
- if something is
false/null/Nal/undefined/""/0
then it will return this value and won't continue to the next expression (as expected) - if everything is true it will return the last value
- React doesn't render
bool
just like he doesn't render null, undefined etc. Since that, In case something is false nothing will render, unless something is 0.
Is there any sources that explain this expression?
I missed/wrong at something?
CodePudding user response:
That is the logical AND operator. How it works is very simple.
- Evaluate the expression on the left.
- If the value of the expression on the left is falsy
- Return the value of the expression on the left.
- Else
- Evaluate and return the value of the expression on the right.
Notice how the expression on the right in only evaluated if the expression on the left is truthy. This is important. That means that if the left operand is falsy, the code on the right never executes. This is called short circuit evaluation.
This is very handy for only doing something when some value is truthy.
// someAction will only be executed if condition is true.
condition && someAction()
When chained you can think of it this way: Return The first falsy value, if none return the last value.
const a = 1
const b = 0
const c = 'qwerty'
const foo = a && b && c && 'test'
In this example foo
is 0
, because that is the first falsy value in the chain.
However, in this code:
const a = 1
const b = 2
const c = 'qwerty'
const foo = a && b && c && 'test'
foo
is test
because all values were truthy, so the last value is returned.
In React, it's often used to conditionally render a component. For example:
{ currentUser && hasAccessToContactInfo && <ContactInfo user={currentUser} /> }
This works because react will not render most* falsy values, so if currentUser
is false
, then the whole expression evaluates to { false }
which doesn't render anything.
This is nice because it allows patterns that make sense in plain javascript to also make sense in React rendering.
* React definitely renders 0
as a text node, which makes sense. It may also render ''
(empty string) as an empty text node, maybe. But most falsy values that dont make sense to render are ignored as you expect.
CodePudding user response:
Of course, is called conditional rendering and it is on React documentation
If you have many fields that form the condition, I would recommend extracting them into a function to improve readability:
const shouldRenderX = () => aField && aFunc() && aVal > another;
...
{ shouldRenderX() && <X>... }