Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js, how to submit a form to another page?

(Next.js) I have a GET form on one page. I want to submit it to another page. I know I can set the action property to the other page. That works. However, it does a page reload instead of just rendering the new page; the same as would happen if you had a link on the page without wrapping it in a Link component.

I could catch the submit event, build a query, and push it onto the router. But that seems like a lot of extra work for something I assume has already been figured out.

Any ideas how to do this without reinventing the wheel?

<form method='get' action='/search'>
  <input name='q' placeholder='Search' arial-label='Search' />
</form>
like image 813
Cully Avatar asked Jan 23 '20 23:01

Cully


People also ask

Is Next.js multi page application?

It turns out that Next. Js is intended to be used for multi-page apps. The author explains how it is possible to use the React Router to make a single-page app with Next.

Does next JavaScript have NavLink?

One of the first components I create while making a new NextJS application is a NavLink component. This component wraps Next's next/link component and adds an activeClassName if that link is active.

Can Next.js do client side rendering?

Rendering can take place on the server or on the client. It can happen either ahead of time at build time, or on every request at runtime. With Next. js, three types of rendering methods are available: Server-Side Rendering, Static Site Generation, and Client-Side Rendering.


1 Answers

I ended up catching the submit event and pushing a URL onto the router.

import {useState} from 'react'
import {useRouter} from 'next/router'

const preventDefault = f => e => {
  e.preventDefault()
  f(e)
}

export default ({action = '/search'}) => {
   const router = useRouter()
   const [query, setQuery] = useState('')

   const handleParam = setValue => e => setValue(e.target.value)

   const handleSubmit = preventDefault(() => {
     router.push({
       pathname: action,
       query: {q: query},
     })
   })

   return (
     <form onSubmit={handleSubmit}>
       <input
         type='text'
         name='q'
         value={query}
         onChange={handleParam(setQuery)}
         placeholder='Search'
         aria-label='Search'
       />
     </form>
   )
}

like image 161
Cully Avatar answered Oct 19 '22 18:10

Cully