最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change routes in gatsby without Link component? - Stack Overflow

programmeradmin4浏览0评论

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 user12200634user12200634
Add a ment  | 

2 Answers 2

Reset to default 14

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>
  )
}
发布评论

评论列表(0)

  1. 暂无评论