(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>
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.
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.
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.
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>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With