Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to hide components in React.js

Say you are passing a prop called show to a component. If the prop value is true, you should render the full component normally. If it is false, you should not display anything.

You can do this two ways.

  1. return null in the render method of the component.
  2. apply a CSS class containing display: none attribute to the component's DOM element.

Which ones is the correct or the preferred way?

like image 737
Anusha Dharmasena Avatar asked Jun 15 '17 06:06

Anusha Dharmasena


1 Answers

I do not think there will be any definite answer for this question. Each approach has its benefits and drawbacks.

With CSS you have:

  • it might work faster
  • no need to think about restoring child control states if control is shown again.

With returning null:

  • the total rendered DOM might be considerably smaller. This is important if you have many such components that might be hidden.
  • there will be no collisions in rendered html. Lets say you have tabular view. Each tab is its own complex form with many child controls. If you have some raw javascript/jquery/whatever working with their ids/classnames etc. - its quite hard to ensure each tab/form has unique ids, unless you do not render them.

From my point of view the decision will be based upon the structure of your control. If it have complex structure with many nested children and you do not have any means of restoring their states when switched on again - go with CSS, but I would say this is a short term solution for quite simple controls only. In all other cases I would go with not rendering a component.

like image 61
Amid Avatar answered Oct 29 '22 07:10

Amid