I have a controlled form in react. When the user submits the form, in the handleSubmit
run, In that function I want to redirect/take them to a new url or page, where url is same as their input value.
For example user types "hello", then when the form submits I want to take them to
/hello
It seems like </Link>(gatsby)
ponent won't work in here. So how do I change route without a Link
Component
This is for a search bar
I have a controlled form in react. When the user submits the form, in the handleSubmit
run, In that function I want to redirect/take them to a new url or page, where url is same as their input value.
For example user types "hello", then when the form submits I want to take them to
http://example./hello
It seems like </Link>(gatsby)
ponent won't work in here. So how do I change route without a Link
Component
This is for a search bar
Share Improve this question edited Jan 12, 2020 at 14:36 asked Jan 6, 2020 at 16:31 user12200634user122006342 Answers
Reset to default 14You should import the navigate API to push/replace the history stack, in order to carry out navigation.
import { navigate } from 'gatsby'
And this is how you can use it, on your form submit method. It is similar to React-Router's history.push()
.
submit() {
// rest of your form logic
navigate('/hello');
}
If you wish to replace the history stack, you may use navigate('/hello', { replace: true })
instead.You may refer to the Gatsby Link documentation for more details.
You can use Gatsby's navigate
helper function.
For example:
import React, { useState } from "react"
import { navigate } from "gatsby"
const Form = () => {
const [value, setValue] = useState("")
return (
<form
onSubmit={event => {
event.preventDefault()
navigate(`/${value}`)
}}
>
{/* here goes your input that sets its value to state with `setValue` */}
</form>
)
}