Show or Hide Element in React



In this article, we are going to cover the implementation of dynamically showing or hiding elements in React. To understand this concept, you must be familiar with hooks in React. By leveraging hooks like useState, you can toggle and update the state to effectively control the visibility of an element.

Approaches to Show or Hide Elements in React

Using && Operator

We have to change the state when a button is clicked, then it will determine the visibility of the element. With the help of conditional rendering and ternary operator, we can ensure the visibility of elements based on the current state.

Example Code

// ToggleElement.jsx

import React, { useState } from 'react';

function ToggleElement() {
  const [isVisible, setIsVisible] = useState(false);

  return (
    <div>
      <button onClick={() => setIsVisible(!isVisible)}>
        {isVisible ? 'Hide Element' : 'Show Element'}
      </button>

      {isVisible && <p>This is a dynamically shown element!</p>}
    </div>
  );
}

export default ToggleElement;

Output

Using && Operator

Using return null

Here we pass the isVisible as a prop to the ChildComponent to control whether the component should be rendered or not. If isVisible is false, the component immediately returns null, effectively preventing it from being displayed. If isVisible is true, the component renders the element.

Example Code

// App.jsx

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

function App() {
  const [isVisible, setIsVisible] = useState(false);

  const toggleVisibility = () => {
    setIsVisible(prevState => !prevState);
  };

  return (
    <div>
      <button onclick="{toggleVisibility}">
        {isVisible ? 'Hide Child Component' : 'Show Child Component'}
      </button>

      <ChildComponent isvisible="{isVisible}"></ChildComponent>
    </div>
  );
}

export default App;
// ChildComponent.jsx

import React from 'react';

function ChildComponent({ isVisible }) {
  if (!isVisible) {
    return null;
  }

  return <div>This is a child component.</div>;
}

export default ChildComponent;

Output

Using return null

Updated on: 2024-12-16T10:35:15+05:30

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements