John B
John B

Reputation: 99

Best way to route after delay in React?

I'm looking to trigger a route to another page in React (using React Router) after an animation is triggered. Off the top of my head, I know I can trigger the animation and Route after a setTimeout is complete, but something tells me that is not a good way to do it. Am I wrong about that, or is there a better way to cause a delay in routing to another page?

An example of what I'm thinking:

target.style.animation = 'example';
setTimeout(() => {
   //Route here
}, 2500);

Upvotes: 1

Views: 960

Answers (1)

Matthew Brooks
Matthew Brooks

Reputation: 571

Assuming you're on a recent version of React, you can use the useHistory hook from react-router to programmatically navigate by calling history.push("/my-next-route") in your setTimeout callback. Check out the official docs for an example.

If your animation is already working and all you need to do is add the actual navigation part, that should get you there. If you want to know the "right" way to do this, you'll need to post more code so we can see exactly what you're trying to accomplish. There are some libraries for handling animations in React, and some others that help combine that with routing, but I can't recommend that as a solution without more context.

Upvotes: 2

Related Questions