'React Link To button timeout
I have a simple button that when I click him he redirect me to another page in the website
now using react router ( <Link to=''>). now what's I want is when I click the button he wait 3 seconds and then redirect me
how can I accomplish this?
Thanks
Solution 1:[1]
You could create a custom link component that takes an additional delay.
Example:
Use a click handler to prevent the default link action so you can "inject" your delayed navigation. Use a React ref to store a reference to the timer and a mounting useEffect hook to clear any running timers in the case the component is unmounted prior to expiration. Use the useNavigate hook to then imperatively navigate with all the appropriate parameters.
import { Link } from 'react-router-dom';
const DelayedLink = ({ delay, replace, state, to, ...props }) => {
const navigate = useNavigate();
const timerRef = useRef();
useEffect(() => () => clearTimeout(timerRef.current), []);
const clickHandler = (e) => {
e.preventDefault();
timerRef.current = setTimeout(navigate, delay, to, { replace, state });
};
return <Link to={to} {...props} onClick={clickHandler} />;
};
Usage:
<DelayedLink delay={3000} to="/test">
Test
</DelayedLink>
<DelayedLink delay={3000} to="/test" state="foobar">
Test w/state
</DelayedLink>
<DelayedLink to="/test">Test w/o delay</DelayedLink>
Solution 2:[2]
Sounds like you want to use setTimeout. If you wrap setTimeout around your button's onClick method then you will be able to introduce a delay.
For example, here's a button which when you click it it waits 3 seconds (3000 milliseconds) before opening Stack Overflow in another tab:
<button
onClick={() => setTimeout(() => window.open("https://stackoverflow.com/"), 3000)}
>
Click me!
</button>
Solution 3:[3]
<button
onClick={() => setTimeout(() => window.open("url", '_blank'), 3000)}
>
I will run after 3 seconds
</button>
This will work!
or try with the useNavigate in react-router-dom
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Reese |
| Solution 2 | Cameron Ford |
| Solution 3 | dinesh oz |
