Techniques to Show and Hide Elements in React

React’s component-based architecture provides an intuitive way to manage UI elements. One of the common requirements in building web applications is the ability to show or hide elements based on certain conditions or user actions. In this article, we’ll explore different methods to show and hide elements in React.

1. Using Conditional Rendering

The simplest way to display or hide elements in React is by using JavaScript’s conditional operators.

Using the Ternary Operator:
function Greeting({ isUserLogged }) {
  return (
    <div>
      {isUserLogged ? <p>Welcome back!</p> : <p>Please log in.</p>}
    </div>
  );
}
Using Logical AND Operator:

If you only want to render an element when a certain condition is met:

function Notification({ message }) {
  return (
    <div>
      {message && <p>{message}</p>}
    </div>
  );
}

2. Using CSS

Another approach is to render all the elements, but use CSS to control their visibility.

Using display property:
function Modal({ isVisible }) {
  return (
    <div style={{ display: isVisible ? 'block' : 'none' }}>
      This is a modal!
    </div>
  );
}
Using visibility property:
function Tooltip({ isHovered }) {
  return (
    <div style={{ visibility: isHovered ? 'visible' : 'hidden' }}>
      Tooltip information here.
    </div>
  );
}

3. Using React’s State

For dynamic show and hide operations based on user interactions, React’s state is often utilized.

class ToggleElement extends React.Component {
  state = {
    isVisible: false
  };

  toggleVisibility = () => {
    this.setState(prevState => ({ isVisible: !prevState.isVisible }));
  };

  render() {
    return (
      <div>
        <button onClick={this.toggleVisibility}>
          Toggle
        </button>
        {this.state.isVisible && <p>Now you see me!</p>}
      </div>
    );
  }
}

4. Using Higher-Order Components (HOC)

A HOC is a function that takes a component and returns a new component with additional props or behavior.

function withVisibilityToggle(WrappedComponent) {
  return class extends React.Component {
    state = {
      isVisible: true
    };

    toggleVisibility = () => {
      this.setState(prevState => ({ isVisible: !prevState.isVisible }));
    };

    render() {
      return (
        <>
          <button onClick={this.toggleVisibility}>Toggle</button>
          {this.state.isVisible && <WrappedComponent {...this.props} />}
        </>
      );
    }
  };
}

// Usage
const VisibleComponent = withVisibilityToggle(YourComponent);

5. Using React’s Context API

If the visibility status needs to be shared across distant components, the Context API is an ideal solution.

const VisibilityContext = React.createContext();

function App() {
  const [isVisible, setVisibility] = React.useState(true);

  return (
    <VisibilityContext.Provider value={{ isVisible, setVisibility }}>
      <ChildComponent />
    </VisibilityContext.Provider>
  );
}

function ChildComponent() {
  const { isVisible, setVisibility } = React.useContext(VisibilityContext);

  return (
    <div>
      <button onClick={() => setVisibility(!isVisible)}>Toggle</button>
      {isVisible && <p>This is a child component.</p>}
    </div>
  );
}

Conclusion

Whether you choose conditional rendering, CSS properties, React’s state, HOCs, or the Context API, the key is to select the approach that best fits your application’s requirements. Often, a combination of these methods offers the most flexible and maintainable solution.

Leave a Comment

Your email address will not be published. Required fields are marked *

Let's Get in Touch

Read our customer feedback

Please fill in the form below.


    To top