Categories
React Answers

How to remove an element from DOM after set amount of time with React?

Spread the love

Sometimes, we want to remove an element from DOM after set amount of time with React.

In this article, we’ll look at how to remove an element from DOM after set amount of time with React.

How to remove an element from DOM after set amount of time with React?

To remove an element from DOM after set amount of time with React, we can use the setTimeout function in the useEffect hook callback.

For instance, we write:

import React, { useEffect, useState } from "react";

const Expire = ({ delay, children }) => {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    setTimeout(() => {
      setVisible(false);
    }, delay);
  }, [delay]);

  return visible ? <div>{children}</div> : <div />;
};

export default function App() {
  return <Expire delay={1000}>123</Expire>;
}

We create the Expire component that has the visible state to control whether the div is visible or not.

Next, we call useEffect with a callback that calls setTimeout with a callback that calls setVisible to false to set visible to false.

We use delay as the value of the delay to run the setTimeout callback.

Now we only display the div with the children inside only when visible is true.

Finally, in App, we render the Expire component with delay set to 1000 to show 123 for 1 second.

Conclusion

To remove an element from DOM after set amount of time with React, we can use the setTimeout function in the useEffect hook callback.

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 *