Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

React components can be hidden or shown without causing re-renders by using the CSS property "display" to toggle the visibility of the component. Instead of changing the component's state, this approach manipulates the CSS style. This way, the component is not re-rendered, and it remains in the virtual DOM.

Here's an example:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true
    };
  }

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

  render() {
    const { visible } = this.state;

    return (
      <div>
        <button onClick={() => this.toggleVisibility()}>
          Toggle visibility
        </button>
        <div
          style={{ display: visible ? "block" : "none" }}
        >
          Hidden content
        </div>
      </div>
    );
  }
}

In this example, the div element with the "Hidden content" text is hidden or shown depending on the current value of the visible state property. The style of the div element is changed using the inline style {{display: visible ? "block" : "none"}}. When the user clicks on the "Toggle visibility" button, the toggleVisibility method is called, which updates the visible state property. However, the component doesn't re-render because only the style of the div element changes.