When you click a link, the browser tries to redirect the user ASAP. How can I add a 1 second delay to this process?
<Link
to={{
pathname: `pathname`,
hash: `#hash`,
}}
onClick={this.delayRedirect}
>
import { withRouter } from 'react-router'
class Home extends Component {
delayRedirect = event => {
const { history: { push } } = this.props;
event.preventDefault();
setTimeout(()=>push(to), 1000);
}
};
<Link
to={{
pathname: `pathname`,
hash: `#hash`,
}}
onClick={this.delayRedirect}
>
}
export default withRouter(Home);
Use history to push new route after a gap of second
Here is my function component version, based on @Shishir's answer:
import React from "react";
import { Link, useHistory } from "react-router-dom";
export default function CustomLink({ to, children }) {
const history = useHistory();
function delayAndGo(e) {
e.preventDefault();
// Do something..
setTimeout(() => history.push(to), 300);
}
return (
<Link to={to} onClick={delayAndGo}>
{children}
</Link>
);
}
Based on Pedro's answer, here's a way to add the delayAndGo function inside a component like a NavBar:
import React from "react"; import { Link, useHistory } from "react-router-dom"; export default function NavBar() { const history = useHistory(); function delayAndGo(e, path) { e.preventDefault(); // Do something.. setTimeout(() => history.push(path), 300); } return ( <Link to="/" onClick={(e) => delayAndGo(e, "/")}> </Link> <Link to="/about" onClick={(e) => delayAndGo(e, "/about")}> </Link> </Link> <Link to="/portfolio" onClick={(e) => delayAndGo(e, "/portfolio")}> </Link> ); }
Note the to
value of the Link
elements do not matter in this approach.
import loadable from '@loadable/component'
import pMinDelay from 'p-min-delay'
npm install p-min-delay
npm i @loadable/component
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.