1.

What is the output of the following code

Answer»

import React from "react"; import ReactDOM from "react-dom"; import "./styles.css"; function APP() { const check = 0; // 0, "", null, undefined return ( <div className="App"> { check && <span>Hello</span> } </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);

This will render 0 to the browser.

  • When using CONDITIONAL rendering using LOGICAL && operator 0 is evaluated as number and will be rendered by the browser
  • How we can avoid rendering 0 in the above case.

We need to make the 0 a Boolean by adding !. Code is given below

import React from "react"; import ReactDOM from "react-dom"; import "./styles.css"; function App() { const check = 0; // 0, "", null, undefined return ( <div className="App"> { !check && <span>Hello</span> } </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);


Discussion

No Comment Found