Divad
Divad

Reputation: 283

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.

Upvotes: 0

Views: 2242

Answers (2)

jon doe
jon doe

Reputation: 544

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"
      />
  )
}

Upvotes: 0

Quentin
Quentin

Reputation: 943217

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>
  )
}

Upvotes: 4

Related Questions