Donghui Ma Donghui Ma - 1 year ago 98
Javascript Question

What will be rendered/sent to ReactDOM.render() as a parament if there is a js injection with Logical Operators inside

so, here is the code

import React from 'react';
import ReactDOM from 'react-dom';

// judgmental will be true half the time.
const judgmental = Math.random() < 0.5;

const favoriteFoods = (
<div>
<h1>My Favorite Foods</h1>
<ul>
{<li>Sushi Burrito</li>}
<li>Rhubarb Pie</li>
{burp && <li>Not Decent</li>}
<li>Broiled Grapefruit</li>
</ul>
</div>
);

ReactDOM.render(
favoriteFoods,
document.getElementById('app')
);


Me and my friend has a different opinion on what exactly will be sent to
ReactDOM.render
as a parameter when burp is
false
.

Here is mine: inside if the JS injection, when burp is false, Logical operator should return burp as in
false
so the JSX will look like

const favoriteFoods = (
<div>
<h1>My Favorite Foods</h1>
<ul>
{<li>Sushi Burrito</li>}
<li>Rhubarb Pie</li>
{burp}
//burp is a false, not even a JSX element
<li>Broiled Grapefruit</li>
</ul>
</div>
);


This will be sent to
ReactDOM.render
and the reason it is not rendered is that
{burp}
as in
{false}
is not JSX, therefore, not showing on screen.

My friend, however, see it in this way: The reason why that part of code is not running is that here I quote


both sides have to be true for the code to run


because the whole logical operator evacuated
false
therefore this part of the code is invalid. He sees this as a boolean calculation. The JSX would be like

const favoriteFoods = (
<div>
<h1>My Favorite Foods</h1>
<ul>
{<li>Sushi Burrito</li>}
<li>Rhubarb Pie</li>
//nada, this code evacated false so it will not run at all.
<li>Broiled Grapefruit</li>
</ul>
</div>
);


This will be sent to ReactDOM.render and the reason it is not rendered is that
{burp && <li>Not Decent</li>}
evacuated to false, this code won't run, therefore, not showing on screen.

I believe I am right but since he is a pro and I just start learning JSX two hours ago. someone help!

Answer Source

You are correct. From the React docs on conditional rendering:

... in JavaScript, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download