Reputation: 43
I already know what is the result of this, but I can't understand what type of logic is, is this a if or something similar?
{touched &&
((error && <span>{error}</span>) ||
(warning && <span>{warning}</span>))}
from
<div>
<label>{label}</label>
<div>
<input {...input} placeholder={label} type={type} />
{touched &&
((error && <span>{error}</span>) ||
(warning && <span>{warning}</span>))}
</div>
Upvotes: 0
Views: 60
Reputation: 3257
First, if touched
is false, the rest of the expression is ignored and nothing is rendred.
If error
evaluated to true
, then error && <span>{error}</span>
is truthy (since React element is truthy too), and <span>{error}</span>
is rendered. In this case the second warning && <...>
does not get evaluated.
If error
is falsy, then the warning && <span>{warning}</span>
is evaluated, and if warning
is truthy the <span>{warning}</span>
gets rendered.
What the doc says on this: https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator:
true && expression always evaluates to expression, and false && expression always evaluates to false.
Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.
You can achieve the same outside of jsx expression:
let element;
if (touched) {
if (error) element = <span>{error}</span>;
else if (warning) element = <span>{warning}</span>;
}
return (
<div>
<input {...input} placeholder={label} type={type} />
{element}
</div>
)
Upvotes: 0
Reputation: 22895
In javascript, &&
operator stops on first false value and returns that value. but ||
keeps looking until it founds a truthy value.
e.g.
true && 1 && 0; // 0
true && 1 && 'Hello'; // 'Hello'
false && true; // false
true || false || 1; // true
false || 'something'; // 'something'
So in this case you are showing error or warning only if field is touched
so it will move onward only if touched
is true
.
When touched
will be true
then it will look for error
and if it is false
, ||
operator will return next value which is warning.
Upvotes: 2
Reputation: 217
They are [logical && expression]
syntax used in React.
To put it in a way so you can understand it easier:
if (touched) {
if (error) {
display(error)
} else if (warning) {
display(warning)
}
}
Upvotes: 0
Reputation: 2648
It’s similar to:
if (touched) {
if (error) {
// error
} else if (warning) {
// warning
}
}
It’s showing error / warning, if there’s any, when field is touched.
Upvotes: 0
Reputation: 1989
Those are stating "display an error and/or warning span, if and only if the error/warning is defined". The idea is that the span is not created if warning/error are null/undefined.
Upvotes: 0