Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delay the redirect of a React Router Link component for 1 second?

When you click a link, the browser tries to redirect the user ASAP. How can I add a 1 second delay to this process?

I have the following link:

  <Link
    to={{
      pathname: `pathname`,
      hash: `#hash`,
    }}
    onClick={this.delayRedirect}
  >

Here is what my delayRedirect function looks like:

  delayRedirect() {
    // not sure what to put here, to delay the redirect by 1 second
  }

Any ideas? Thanks!

like image 816
Ralph David Abernathy Avatar asked Oct 24 '25 00:10

Ralph David Abernathy


2 Answers

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

like image 105
Shishir Arora Avatar answered Oct 26 '25 23:10

Shishir Arora


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>
  );
}
like image 42
Pedro Netto Avatar answered Oct 27 '25 01:10

Pedro Netto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!