Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ Enhancing UX: Leveraging Nextjs Router Events for Form Manipulation

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š Enhancing UX: Leveraging Nextjs Router Events for Form Manipulation


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

Scenario ๐Ÿ’ป

When manipulating form data with a considerable number of input fields
whether it be five, ten, or even more than twenty or thirty field and it can be quite frustrating for users.

Imagine a scenario where a user has filled out 12 out of 20 fields, and then, unintentionally, they click on another link or navigate to a different page, resulting in the loss of all the entered data.

Image description

"Consider a scenario where you manipulate a form, and then, when you attempt to click on a different item in the left menu navbar, a custom popup should appear to prevent you from leaving the current page."

Image description

In the example below, I'll demonstrate a simple layout created using Mantine and Next.js. To address this issue, we'll implement a solution that displays a custom popup when attempting to leave the current page with unsaved form data.

"next": "13.4.13",
"@mantine/modals": "^6.0.15",
"@mantine/next": "^6.0.15",
"@mantine/notifications": "^6.0.15",`

Manipulate ๐Ÿ’ป

We will use the router event to manipulate, so you might want to conduct some research on 'Router events' in Next.js.

You can listen to different events happening inside the Nextjs Router and subscribe to router events on any component in your application.

as mentioned in the Next.js router documentation.

For example, to listen to the router event routeChangeStart, open or create pages/_app.js and subscribe to the event, like so:

import { useEffect } from 'react'
import { useRouter } from 'next/router'

export default function MyApp({ Component, pageProps }) {
  const router = useRouter()

  useEffect(() => {
    const handleRouteChange = (url, { shallow }) => {
      console.log(
        `App is changing to ${url} ${
          shallow ? 'with' : 'without'
        } shallow routing`
      )
    }

    router.events.on('routeChangeStart', handleRouteChange)

    // If the component is unmounted, unsubscribe
    // from the event with the `off` method:
    return () => {
      router.events.off('routeChangeStart', handleRouteChange)
    }
  }, [router])

  return <Component {...pageProps} />
}

Now, let's apply this technique to our source code:

import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { modals } from '@mantine/notifications';

const YourComponent = () => {
  const router = useRouter();
  const [isSubmitSuccess, setIsSubmitSuccess] = useState(false);

  const handleSubmitForm = (params) => {
    // Process params and call the API
    // After success, redirect to the homepage
    setIsSubmitSuccess(true);
    router.push('/');
  };

  const exitingFunction = (nextPath) => {
    // If the submission is successful, 
    // No need to prevent the router
    if (isSubmitSuccess) {
      return;
    }

    // Display a confirmation popup before discarding changes
    modals.openContextModal({
      modal: 'confirm',
      withCloseButton: false,
      innerProps: {
        title: 'Discard changes',
        message: 'Are you sure you want to discard changes?',
        onOk: () => {
          removeListener();
          modals.closeAll();
          router.push(nextPath);
        },
      },
    });

    // Throw an error to prevent the router change
    throw 'cancelRouteChange';
  };

  const removeListener = () => {
    setIsSubmitSuccess(false);
    router.events.off('routeChangeStart', exitingFunction);
  };

  useEffect(() => {
    router.events.on('routeChangeStart', exitingFunction);
    return removeListener;
  }, [isSubmitSuccess, router]);

  return (
    <form onSubmit={handleSubmitForm}>
      {/* Your form fields go here */}
      <button type="submit">Submit</button>
    </form>
  );
};

export default YourComponent;

The Route Cancellation Mechanism๐Ÿ’ป

The line throw 'cancelRouteChange';is used as a mechanism to prevent the router change. In the context of the provided code, this line is employed when the user attempts to leave the current page without submitting the form.

By throwing an error with the message 'cancelRouteChange', the application signals that the route change should be canceled.

This approach aligns with how Next.js handles route changes. When an error is thrown during a route change, Next.js interprets it as a signal to stop the navigation process.

In conclusion, we've explored the powerful combination of Next.js Router Events and custom popups to create a more secure and user-friendly form interaction experience. By intercepting page transitions and providing users with the option to confirm or cancel, we've added an extra layer of protection against inadvertent data loss.

Thank you for joining me on this exploration! This marks my first attempt at sharing knowledge, and I look forward to many more opportunities to learn and grow together.๐Ÿ™‹โ€โ™‚๏ธ
Happy coding!๐Ÿ’ป

...



๐Ÿ“Œ Enhancing UX: Leveraging Nextjs Router Events for Form Manipulation


๐Ÿ“ˆ 79.23 Punkte

๐Ÿ“Œ What is NextJs?ย  Why Should You Use it in 2023?ย  NextJs Pros and Cons Guide


๐Ÿ“ˆ 31.65 Punkte

๐Ÿ“Œ NextJS examples: 60 popular websites built with NextJS and headless CMS


๐Ÿ“ˆ 31.65 Punkte

๐Ÿ“Œ 3 Exciting Improvements Between NextJS 14 And NextJS 13


๐Ÿ“ˆ 31.65 Punkte

๐Ÿ“Œ CVE-2024-1122 | Event Manager, Events Calendar, Events Tickets for WooCommerce Plugin Events Export authorization (ID 3033231)


๐Ÿ“ˆ 29.83 Punkte

๐Ÿ“Œ Cgiscript.net csMailto csMailto.cgi form-to/form-from/form-results privilege escalation


๐Ÿ“ˆ 26.59 Punkte

๐Ÿ“Œ Leveraging AI: Advanced Tools and Integrations for Enhancing SaaS Products


๐Ÿ“ˆ 26.37 Punkte

๐Ÿ“Œ Leveraging Travel Booking APIs for Tourism Providers: Enhancing the Customer Experience


๐Ÿ“ˆ 26.37 Punkte

๐Ÿ“Œ Enhancing Cyber Resilience in Banking: Leveraging Live Patching to Combat Rising Threats


๐Ÿ“ˆ 26.37 Punkte

๐Ÿ“Œ How to create a free email subscription form in NextJS, Netlify and MailerLite


๐Ÿ“ˆ 24.69 Punkte

๐Ÿ“Œ Tutorial: Build a contact form with NextJS and BCMS


๐Ÿ“ˆ 24.69 Punkte

๐Ÿ“Œ Submitting a form in Nextjs 14 with onBlur, server actions, and validation


๐Ÿ“ˆ 24.69 Punkte

๐Ÿ“Œ Leveraging Next.js and Firebase to Fetch Upcoming Events: A Deep Dive


๐Ÿ“ˆ 23.43 Punkte

๐Ÿ“Œ NextJS App Router with Pocketbase SSR setup


๐Ÿ“ˆ 22.65 Punkte

๐Ÿ“Œ Add Metadata in NextJS App router for nested pages


๐Ÿ“ˆ 22.65 Punkte

๐Ÿ“Œ Migrating from Create React App(CRA) to NextJS (Pages Router)


๐Ÿ“ˆ 22.65 Punkte

๐Ÿ“Œ Next Js TopLoader :- Add TopLoader to NextJS App Router


๐Ÿ“ˆ 22.65 Punkte

๐Ÿ“Œ [APPSEC-1900] Remote code execution by leveraging 1st stage unsanitized form input


๐Ÿ“ˆ 22.34 Punkte

๐Ÿ“Œ Enhancing Shopify Functionality with the Ultimate API-Integrated Contact Form Plugin


๐Ÿ“ˆ 21.75 Punkte

๐Ÿ“Œ Leveraging the Loading UI in Next.js App Router


๐Ÿ“ˆ 20.31 Punkte

๐Ÿ“Œ Bug Bounty Hunting - Wfuzz - Web Content Discovery & Form Manipulation


๐Ÿ“ˆ 20.26 Punkte

๐Ÿ“Œ Content*Builder events/events.inc.php lang_path privilege escalation


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ Low CVE-2013-7480: Wp-events-plugin Events manager


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ Low CVE-2013-7479: Wp-events-plugin Events manager


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ dotCMS 3.7.0 /news-events/events date Cross Site Scripting


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ Low CVE-2013-7478: Wp-events-plugin Events manager


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ Low CVE-2013-7477: Wp-events-plugin Events manager


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ dotCMS 3.7.0 /news-events/events date cross site scripting


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ Events Manager Plugin up to 5.8.1.1 on WordPress events-manager.js mapTitle cross site scripting


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ CVE-2023-52142 | Cool Plugins Events Shortcodes for the Events Calendar Plugin up to 2.3.1 on WordPress sql injection


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ Fix โ€œNot authorized to send Apple events to System Eventsโ€ Mac Error


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ Events Manager Plugin bis 5.8.1.1 auf WordPress events-manager.js mapTitle Cross Site Scripting


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ CVE-2018-25076 | Events Extension on BigTree classes/events.php sql injection


๐Ÿ“ˆ 19.89 Punkte

๐Ÿ“Œ Events Manager Plugin bis 5.8.1.1 auf WordPress events-manager.js mapTitle Cross Site Scripting


๐Ÿ“ˆ 19.89 Punkte











matomo