简体   繁体   中英

How to change routes in gatsby without Link component?

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.com/ hello

It seems like </Link>(gatsby) component won't work in here. So how do I change route without a Link Component

This is for a search bar

You 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>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM