Search code examples
reactjshidetailwind-csssnackbar

How to hide element in 2 seconds in React


I use Tailwind-css and React and want to hide div-element after 2 seconds. The user press the button and a snackbar apears for 2 sec to show that the suggestion was sent. I use setTimeout but it is not correct variant. Function Snackbar get props whether snackbar open (snackbar = true), message on the snackbar (suggestResponse.message) and should sent if snackbarClose (false)

const SnackbarResult = ({
  snackbar,
  snackbarClose,
  suggestResponse,
}: ISnackbarProps) => {
  if (snackbar) {
    setTimeout(() => snackbarClose, 2000);
  }
  if (!snackbar) return null;
  return (
    <div className="bg-green-500 fixed right-2 bottom-1 font-medium p-2 md:p-5">
      {suggestResponse.message}
    </div>
  );
};

Solution

  • You should put setTimeout inside the useEffect so you can clear the timeout when component re-render or un mount.

    useEffect(() => {
      if (snackbar) {
        const timeout = setTimeout(() => snackbarClose(), 2000);
        return () => {
          clearTimeout(timeout);
        };
      }
    }, [snackbar]);