Categories
React Answers

How to show or hide React components without losing their internal state?

Spread the love

Sometimes, we want to show or hide React components without losing their internal state.

In this article, we’ll look at how to show or hide React components without losing their internal state.

How to show or hide React components without losing their internal state?

To show or hide React components without losing their internal state, we can set the display CSS property to 'none' to hide the component.

For instance, we write:

import React, { useState } from "react";

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <>
      <button onClick={() => setCount((c) => c + 1)}>increment</button>
      <p>{count}</p>
    </>
  );
};

const Counter2 = () => {
  const [count, setCount] = useState(0);

  return (
    <>
      <button onClick={() => setCount((c) => c + 2)}>increment</button>
      <p>{count}</p>
    </>
  );
};

export default function App() {
  const [toggle, setToggle] = useState(true);

  return (
    <>
      <button onClick={() => setToggle((t) => !t)}>toggle</button>
      <div style={{ display: toggle ? "none" : "block" }}>
        <Counter />
      </div>
      <div style={{ display: toggle ? "block" : "none" }}>
        <Counter2 />
      </div>
    </>
  );
}

We have the Counter and Counter2 components that lets us set the count state by clicking on the increment button.

To keep the count value when we show and hide the 2 components, we wrap divs around the 2 components.

And then we set the display CSS property to 'none' or 'block' depending on the toggle state value.

And then we set the object with the display property as the value of the style prop of each div.

This way, the components won’t be taken out of the DOM when we hide them so their states are kept.

Conclusion

To show or hide React components without losing their internal state, we can set the display CSS property to 'none' to hide the component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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