In cases where a Link
doesn’t make sense, but you still need to navigate to a new page — such as a form submission — Gatsby provides a navigate
helper for programmatic navigation. In this video, learn how to:
navigate
helperInstructor: [00:00] In some cases, such as when you're dealing with forms, you won't be using a traditional link. You'll be doing programmatic navigation. For example, when we submit this form, it should take us to a confirmation page. To test that, we can click, and it gives us a surprise.
[00:17] Submitting a form means that we need to handle navigation programmatically. To do this, we're going to use the navigate import from Gatsby. In our sign-up page, we can import navigate from Gatsby. In our handle submit, instead of doing it this way, which is not a great idea, we're instead going to navigate. Where we want to navigate to is our surprise page.
[00:50] Because we've submitted the form, let's include it. We're going to include the state. The state that we want to include is just the name. The name is set up here, in local state. We can then go into the surprise, grab the location out. Let's add the name. We'll do location.state.name.
[01:15] If we go back to our form, we can submit it. We'll see that it remembers what was submitted. It also avoids that jank of fully refreshing the page, giving us a much more app-like experience.