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

When using nextjs rewrites, encountering a 404 error may occur

When attempting to access the development server on from my local environment, I encountered a CORS error while making a call from my nextjs/reactjs app. To resolve this issue, I implemented a reverse proxy in Next.js as shown below: /** @type {import(&ap ...

I would like for this message to appear periodically following the initial execution

I have developed a unique welcome feature using HTML and CSS that I would like to showcase intermittently. --------------------------- My Desired Outcome --------------------------- Initially, this feature should be triggered once (when a user first acce ...

tips for iterating through a json string

When retrieving data from PHP, I structure the return like this: $return['fillable'] = [ 'field_one', 'field_two', 'field_three', 'field_four', 'field_five', ]; $json = json_ ...

populating a HTML image tag 'src' attribute with data extracted from API javascript code

Hey there! I'm currently working on integrating an image element from the openweatherAPI that corresponds to the weather icon retrieved from the JSON data when a user inputs a city. This means displaying images like scattered clouds or clear skies bas ...

Tips for initiating a jQuery form submission

At this moment, the form is being submitted using the default URL. I would like it to utilize the form submit event in my JavaScript code so that it can pass the .ajaxSubmit() options. Below is the corresponding JavaScript code: $('#selectedFile&a ...

When the function $(document).width() is called, it may yield varying results depending on the timing of the call

Every time I use $(document).width(); within $(window).load(function(){}) or $(document).ready(function(){}), the result differs from when it is called inside $(window).resize(function(){}). The discrepancy is approximately 100px, and it's not due to ...

The initial value in useEffect is not being updated by useState

I am currently implementing a like feature for my web application. The issue lies in the fact that my setLike function is not updating the state even after using setLike(!like). I verified this by adding console.log() statements before and after the setLik ...

What techniques can I employ to ensure that withLatestFrom() effectively interacts with itself?

In my program, I have an intermediate stream that is connected to a source, but it can also trigger events from other sources (such as user input). In another part of my code, there is a derived stream that needs to compare new data from the intermediate w ...

What is the best way to include a background image in a div within a React component?

I'm currently following a tutorial on creating an RPG game using React. The tutorial can be found at this link. I am trying to replicate the presenter's code by typing it out myself. However, I'm running into an issue when attempting to add ...

What are some effective techniques to optimize this node.js code and eliminate redundancy?

I am currently in the process of setting up a basic template for my demonstration project and writing my first node.js program. The piece of code below is functioning properly for my initial test, but it contains duplicated sections - Getting connection, E ...

Issue: Database not updating after input via AJAXExplanation: Despite submitting new data through AJAX, the

I've been struggling to display the UPDATED database on my initial html page after submitting new information. Despite successfully updating the database using AJAX, I can only see the outdated version. Any assistance in resolving this issue would be ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

Using HTML, jQuery, and JSON with an AJAX call to populate two web tables stacked on top of each other

I am encountering an issue with populating two tables using two searches based on user input in mySQL-JSON-AJAX. When the user enters a search term and clicks the corresponding button, data should populate the respective table. The problem arises when clic ...

Angular page not reflecting show/hide changes from checkbox

When the user clicks on the checkbox, I need to hide certain contents. Below is the code snippet: <input id="IsBlock" class="e-field e-input" type="checkbox" name="IsBlock" style="width: 100%" #check> To hide content based on the checkbo ...

tips for uploading image data using JavaScript

My HTML form sends POST data to my PHP script and uses AJAX for a live preview The issue arises with the image input field in the form Here's an example of the form structure: <form method="post" action="scripts/test.php" enctype="multipart/form ...

Having trouble with implementing a 64-bit bitwise AND operation in JavaScript?

I've been attempting to perform a bitwise AND operation on long numbers using Javascript. Despite trying the solutions provided at (How to do bitwise AND in javascript on variables that are longer than 32 bit?), none of them have been accurate for the ...

How can the hreflang tag be used correctly in a React application that supports multiple languages?

I have a React application with 3 pages(routes) and I support 2 languages (English and Spanish). Should I insert the following code into the <head></head> section of the public\index.html file like this? <link rel="alternate" ...

Utilizing pop-up alerts and AJAX requests in jQuery forms

I am looking to enhance my website by creating a form using PHP and jQuery. Currently, the form is placed in the footer of my website. However, I want to display the form results in a popup within the main section of the website without requiring a page ...

Unable to organize list of entities based on numerical values

I am working with an array of objects structured like this: [ { "value": 351.68474, "o_p": [ "$.text" ] }, { "value": 348.0095, "o_p": [ ...

How can you set a $_GET variable without having to reload the page?

I have a table on my website that displays values for each row, and here's an example code snippet: //JAVASCRIPT <tr onclick="window.history.replaceState(null, null, 'myPage.php?ID=2');"> The URL changes with this code, but it doesn& ...