javascripthtmlcssreactjsreact-tooltip

React Tooltip doesn't closes when using settimeout


I'm trying to show a tooltip open by default when the component mounts and then close it after 3 seconds using setState and the defaultIsOpen prop. However, the tooltip remains visible after 3 seconds. Here's the code. Any idea what I'm missing?

import { useEffect, useState } from "react";
import { Tooltip } from "react-tooltip";

type CustomTooltipProps = {
  id: string;
  children: React.ReactNode;
  defaultIsOpen?: boolean;
};

function App() {
  const [show, setIsShow] = useState(true);


  useEffect(() => {
    const timer = setTimeout(() => {
      setIsShow(false);
    }, 3000);

    return () => clearTimeout(timer);
  }, []);

  return (
    <>
      <h1 data-tooltip-id="cstm-tooltip">Tooltip Does't closes after 3seconds</h1>
      <CustomTooltip id="cstm-tooltip" defaultIsOpen={show}>
        My Custom Tooltip
      </CustomTooltip>


    </>
  );
}

export default App;




const CustomTooltip: React.FC<CustomTooltipProps> = ({ id, children, defaultIsOpen }) => {
  return (
    <Tooltip id={id} defaultIsOpen={defaultIsOpen}>
      {children}
    </Tooltip>
  );
};

Solution

  • Defaultopen is not reactive which means it only takes the value at first render only so when you change the value later it will not react, you should instead use open prop which is reactive