Is there a way to conditionally show or hide an element?


Is there a way to conditionally show or hide an element?


When using a conditional to render an element, we can return null for a condition to make sure an element does not render based on the condition.

For example:

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

function showOrHide () {
  let myHideObj = {
    hide: false

  if (myHideObj.hide === false) {
    let innerElement = (
      <h1>Not hidden!</h1>  
    return innerElement; // when myHideObj.hide property is set to false the if statement will return innerElement and will render the element
  } else {
    return null; // when myHideObj.hide property is set to true we can return null to make sure no element is rendered based on our condition

const myElement = (

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

I have an one doubt for invoking method in the element.
In the last tutorial you have shown, method name only without specifying () parenthesis.
But this example you shown like method name() with the parenthesis.
Which one is correct? Whether we want to add parenthesis or not while calling method?

1 Like

A method name without parens is a reference to the method, where with parens is a call to invoke the method.

We use the reference when we wish to supply a method with a callback function that will be invoked at some later time.


times_5 = x => x * 5;

arr1 = [2, 3, 4, 5, 6, 7, 8, 9]

arr2 =

// [10, 15, 20, 25, 30, 35, 40, 45]

Notice we pass only the reference to the map iterator method? Internally the method iterates of the array and passes each value to the callback function, which returns a new computed value that ends up in the final array.

We can still run the times_5 function on it own,

console.log(times_5(42))    // 210

Notice this time we do use the parens to pass in our argument.


What is "const myElement = (

)" ? What does it do, why is it there?

myElement is a div that contains the result of executing showOrHide(), so that div can either contain nothing or the “Not Hidden!”

element. myElement is there because passing null to ReactDOM.render() would break the code.