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

Question

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

Answer

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 = (
  <div>{showOrHide()}</div>
)

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

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?

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.

Consider,

times_5 = x => x * 5;

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

arr2 = arr1.map(times_5)

console.log(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.

4 Likes