Skip to content
Advertisement

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.

Advertisement

Answer

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"
      />
  )
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement