简体   繁体   中英

How to redirect to another page using on keypress in nextjs?

I need to redirect users using onkeypress in nextjs.

I have a search input where users can type and then press enter key to go to the other page.

What I've tried:

 const handler = (e) => { const ENTER = 13; if (e.keyCode === ENTER) // do a history.push("/news"); console.log("enter"); }; <input onKeyPress={(e) => handler(e)} type="text" name="search" placeholder="Search by keywords" className="p-4 md:p-6 w-full py-2 md:py-4 border-2 text-lg md:text-2xl xl:text-3xl border-gray-400 outline-none filosofia_italic bg-white placeholder-gray-400" />

i would appreciate your help.

This is covered by the documentation :

Imperatively

next/link should be able to cover most of your routing needs, but you can also do client-side navigations without it, take a look at the documentation for next/router.

The following example shows how to do basic page navigations with useRouter:

 import { useRouter } from 'next/router' export default function ReadMore() { const router = useRouter() return ( <button onClick={() => router.push('/about')}> Click here to read more </button> ) }

You can use the useRouter hook from next - https://nextjs.org/docs/api-reference/next/router

Try changing you handler to

import {useRouter} from "next/router"; const Component = () => { const router = useRouter(); const handler = (e) => {... router.push("/news"); } return ( <input onKeyPress={handler} type="text" name="search" placeholder="Search by keywords" className="p-4 md:p-6 w-full py-2 md:py-4 border-2 text-lg md:text-2xl xl:text-3xl border-gray-400 outline-none filosofia_italic bg-white placeholder-gray-400" /> ) }

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