How can I redirect to a different page with a keypress event in Next.js?

I am looking to implement a redirection function in nextjs when users press a key.

There is a search input field where users can type and then hit the enter key to navigate to another page.

Here's what I have attempted:

  const handleKeyPress = (e) => {
      const ENTER_KEY_CODE = 13;

      if (e.keyCode === ENTER_KEY_CODE)  // perform history.push("/news");
          console.log("Enter key pressed");
  };

   <input
          onKeyPress={(e) => handleKeyPress(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"
        />

Your assistance would be highly appreciated.

Answer №1

The information you need can be found in the official documentation:

Imperative Routing

While next/link is a great tool for most routing tasks, there are situations where you may need to handle client-side navigation differently. In such cases, refer to the documentation for next/router.

Here is an example demonstrating how to perform basic page navigations using useRouter:

import { useRouter } from 'next/router'

export default function LearnMore() {
  const router = useRouter()

  return (
    <button onClick={() => router.push('/about')}>
      Click here to learn more
    </button>
  )
}

Answer №2

If you're looking to enhance your event handling with Next.js, consider utilizing the useRouter hook, which can be found here: https://nextjs.org/docs/api-reference/next/router

Make a tweak to your handler as follows:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I accurately show the server time and timezone in JS/jQuery regardless of the user's location?

Apologies for bringing up another time and timezone question related to web development. Despite numerous resources available, I am still struggling to grasp the concept of converting time between PHP and JavaScript. Here is my scenario: I aim to retrieve ...

Troubleshooting problem with sorting in Angular 4 material header

Using Angular 4 material for a table has presented me with two issues: 1. When sorting a table, it displays the description of the sorting order in the header. I would like to remove this. It displays "Sorted by ascending order" here. The ngx modal theme ...

When there is only one value, the BehaviorSubject can be hit multiple times

Recently, I implemented BehaviourSubject in a shared service to retrieve the current value when clicking a button. Everything seems to be working fine, however, there are instances where the API call within the subscribe block of BehaviourSubject is being ...

Tips for avoiding the automatic transition to the next slide in SwiperJS

How can I prevent the next button click in swiper based on my custom logic? I am using the swiperjs library within a Vue project and I need to stop users from swiping or clicking the next button to move to the next slide depending on certain conditions de ...

Achieving the perfect alignment: Centering a paragraph containing an image using JQuery

I need help centering the background image of my <p> tag on the webpage. Script $(function() { $('ul.nav a').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ ...

Mastering the correct way to handle the "window" object within the Node.js testing environment using JSDom

Testing my React app using Tape and JSDom involves importing a specific module at the beginning of each test JS file: import jsdom from 'jsdom' function setupDom() { if (typeof document === 'undefined') { global.document = jsdom ...

Which is the better approach for performance: querying on parent selectors or appending selectors to all children?

I currently have 2 mirror sections within my DOM, one for delivery and another for pickup. Both of these sections contain identical content structures. Here's an example: <div class="main-section"> <div class="description-content"> ...

Step-by-step guide on creating a personalized logic and redirecting to different pages using the useEffect hook in React or Next.js

I have recently developed a quiz application with three main pages - Junior, Senior, and SuperSenior. Depending on the selection made by the user from the dropdown menu on the homepage, I need to redirect them to the appropriate page. To achieve this func ...

jQuery fade in problem or alternate solutions

When I send a post request to a file and input the response into id='balance', I would like it to have a flickering effect or fadeIn animation to alert the user that it is being updated in real time. I attempted to use the fadeIn() method but it ...

Removing consecutive pipe symbols in JavaScript

Looking for a way to remove excess pipe characters before a certain pattern in JavaScript. var testString="||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||f_test!!3!!||f_test!!4!!||f_test!!5!!||"; output ="||f_test!!3!!| ...

Determine total and showcase it as the range slider is adjusted

Seeking to calculate and present the result of three range sliders. The equation I aim to showcase is: KM driven per year * Avg KM/100L / Price of fuel I have managed to display each slider's individual values, but I am uncertain about how to show t ...

Exploring the capabilities of Node's http/2 client functions in conjunction with webpack

I've been grappling with this issue for the past two days and I'm beyond frustrated. Every time I attempt to import "node:http2" specifically for its client-side functionality, my application crashes because http2 is missing from the webpack bund ...

Speeding up the loading time of my background images

body { background: url(http://leona-anderson.com/wp-content/uploads/2014/10/finalbackgroundMain.png) fixed; background-size:100% auto; } I have unique background images on each of my sites, but they are large in size and take some time to load due to bein ...

Whenever I attempt to trim my integer within a for loop, my browser consistently becomes unresponsive and freezes

I am facing an issue with my code that generates alcohol percentage, resulting in values like 43.000004 which I need to trim down to 43.0, 45.3, etc. However, whenever I try to use any trim/parse functions in JavaScript, my browser ends up freezing. Below ...

AngularJS: Assigning a value to an element

I am facing the challenge of automating an iframe using Selenium Webdriver and need to input a value into a text box. Here is the HTML code: <input class="ng-pristine ng-empty ng-invalid ng-invalid-required ng-valid-maxlength ng-touched" id="name" typ ...

How can I incorporate a fade opacity effect into my Div scrolling feature?

I successfully implemented code to make div elements stick at the top with a 64px offset when scrolling. Now, I am trying to also make the opacity of these divs fade to 0 as they scroll. I am struggling to figure out how to achieve this effect. Below is ...

"Contrasting the Execution of a JavaScript Function in a .js File Versus an HTML

I'm struggling with calling a JavaScript function inside an HTML page. Interestingly, when I move the function into an external file and link it, everything works perfectly. Can someone provide assistance in resolving this issue? Below is the content ...

VueJS's approach to routing through modular components

I am currently working on a website where I need to set up different category pages using dynamic routes. To achieve this, I am utilizing vue-router and aiming for a single dynamic route that can switch between pages by loading different components. Here ...

Comparing JSON objects with JavaScript models: A guide

Currently I'm working with angular 2 and I have an array of data. data: MyModel[] = [ { id: 1, name: 'Name', secondName: 'SecondName' } In addition, I have created the interface MyModel: interface MyModel { id: number, nam ...

Converting RowDataPacket to an array in Node.js and MySQL API, learn how to convert a RowDataPacket from the MySQL API into an array

Hello, I need assistance with converting my row data packet into an array of arrays or nested arrays. Please provide code snippet below: router.get('/getPosts/:user_id', (req, res, next) => { connection.query('SELECT * FROM files WHERE ...