Languages
[Edit]
EN

React - how to show or hide element

3 points
Created by:
Hayley-Mooney
677

In this article, we would like to show you how to show or hide elements in React.

Quick solution:

 

There are to three ways how to show or hide elements in React:

  1. using conditional rendering,
  2. using style property,
  3. using className property.
Hidding and showing element in React.
Hidding and showing element in React.

 

In the below examples, we use buttons that hide and show <div>My element</div> element. We use useState() hook to store the visibility state.

1. Conditional rendering

Edit

Conditional rendering uses {[condition-here] && (...)} JSX construction. When state is changed the component is re-rendered. That approach causes nodes redering/omitting/removing depending on [condition-here] value (true/false). The main advantage of conditional rendering is performance (DOM doesn't contain unused nodes).

1.1. One button solution

Edit

When onClick button event occurs we are able to set new visible state with setVisible(!visible) - clicks hide and show the element.

Practical example:

1.2. Two buttons solution

Edit

One buton is used to display element and second one to hide the same element.

Practical example:

 

2. style property

Edit

style property uses <div style={{display: [condition-here] ? 'block' : 'none'>...</div> JSX construction. In this case the element is not removed - it is just invisible by styles.

Practical example:

 

3. className property

Edit

className property uses <div className={[condition-here] ? 'class-1' : 'class-2'>...</div> JSX construction. In this case the element is not removed - it is just invisible by styles.

Practical example:

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - show or hide element
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join