Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

import { withRouter } from'react-router'classHomeextendsComponent {

  delayRedirect = event => {
      const { history: { push } } = this.props;
      event.preventDefault();
      setTimeout(()=>push(to), 1000);
    }
  };
  <Linkto={{pathname: `pathname`,
      hash: `#hash`,
    }}
    onClick={this.delayRedirect}
  >
}

export default withRouter(Home);

Use history to push new route after a gap of second

Solution 2:

Here is my function component version, based on @Shishir's answer:

importReactfrom"react";
import { Link, useHistory } from"react-router-dom";

exportdefaultfunctionCustomLink({ to, children }) {
  const history = useHistory();

  functiondelayAndGo(e) {
    e.preventDefault();

    // Do something..setTimeout(() => history.push(to), 300);
  }

  return (
    <Linkto={to}onClick={delayAndGo}>
      {children}
    </Link>
  );
}

Solution 3:

Based on Pedro's answer, here's a way to add the delayAndGo function inside a component like a NavBar:

importReactfrom"react";
import { Link, useHistory } from"react-router-dom";

exportdefaultfunctionNavBar() {
  const history = useHistory();

  functiondelayAndGo(e, path) {
    e.preventDefault();

    // Do something..setTimeout(() => history.push(path), 300);
  }

  return (
    <Linkto="/"onClick={(e) => delayAndGo(e, "/")}>
        Home
    </Link><Linkto="/about"onClick={(e) => delayAndGo(e, "/about")}>
        About
    </Link><Linkto="/portfolio"onClick={(e) => delayAndGo(e, "/portfolio")}>
        Portfolio
    </Link>
  );
}

Note the to value of the Link elements do not matter in this approach.

Post a Comment for "How To Delay The Redirect Of A React Router Link Component For 1 Second?"