Navigation function in javascript

Linking and Navigating

. This means navigation maintains client-side state, avoids expensive re-renders, is interruptible, and doesn’t cause race conditions.

There are two ways to navigate between routes:

This page will go through how to use , useRouter() , and dive deeper into how navigation works.

Component

is a React component that extends the HTML element to provide prefetching and client-side navigation between routes. It is the primary way to navigate between routes in Next.js.

To use , import it from next/link , and pass a href prop to the component:

import Link from 'next/link' export default function Page()  return Link href="/dashboard">DashboardLink> >

There are optional props you can pass to . See the API reference for more information.

Examples

Linking to Dynamic Segments

to generate a list of links. For example, to generate a list of blog posts:

import Link from 'next/link' export default function PostList(< posts >)  return (  ul>  posts.map((post) => (  li key=post.id>>  Link href=`/blog/$post.slug>`>>post.title>Link>  li>  ))>  ul>  ) >

You can use usePathname() to determine if a link is active. For example, to add a class to the active link, you can check if the current pathname matches the href of the link:

'use client' import from 'next/navigation' import Link from 'next/link' export function Navigation(< navLinks >)  const pathname = usePathname() return (  <>  navLinks.map((link) =>  const isActive = pathname.startsWith(link.href) return (  Link className= ? 'text-blue' : 'text-black'> href=link.href> key=link.name>  >  link.name>  Link>  )  >)>    ) >

Scrolling to an id

The default behavior of is to scroll to the top of the route segment that has changed. When there is an id defined in href , it will scroll to the specific id , similarly to a normal tag.

useRouter() Hook

The useRouter hook allows you to programmatically change routes inside Client Components.

To use useRouter , import it from next/navigation , and call the hook inside your Client Component:

'use client' import from 'next/navigation' export default function Page()  const router = useRouter() return (  button type="button" onClick= => router.push('/dashboard')>>  Dashboard  button>  ) >

The useRouter provides methods such as push() , refresh() , and more. See the API reference for more information.

Recommendation: Use the component to navigate between routes unless you have a specific requirement for using useRouter .

How Navigation Works

  • A route transition is initiated using or calling router.push() .
  • The router updates the URL in the browser’s address bar.
  • The router avoids unnecessary work by re-using segments that haven’t changed (e.g. shared layouts) from the client-side cache. This is also referred to as partial rendering.
  • If the conditions of soft navigation are met, the router fetches the new segment from the cache rather than the server. If not, the router performs a hard navigation and fetches the Server Component payload from the server.
  • If created, loading UI is shown from the server while the payload is being fetched.
  • The router uses the cached or fresh payload to render the new segments on the client.

Client-side Caching of Rendered Server Components

Good to know: This client-side cache is different from the server-side Next.js HTTP cache.

The new router has an in-memory client-side cache that stores the rendered result of Server Components (payload). The cache is split by route segments which allows invalidation at any level and ensures consistency across concurrent renders.

As users navigate around the app, the router will store the payload of previously fetched segments and prefetched segments in the cache.

This means, for certain cases, the router can re-use the cache instead of making a new request to the server. This improves performance by avoiding re-fetching data and re-rendering components unnecessarily.

Invalidating the Cache

Server Actions can be used to revalidate data on-demand by path ( revalidatePath ) or by cache tag ( revalidateTag ).

Prefetching

Prefetching is a way to preload a route in the background before it’s visited. The rendered result of prefetched routes is added to the router’s client-side cache. This makes navigating to a prefetched route near-instant.

By default, routes are prefetched as they become visible in the viewport when using the component. This can happen when the page first loads or through scrolling. Routes can also be programmatically prefetched using the prefetch method of the useRouter() hook.

Static and Dynamic Routes:

  • If the route is static, all the Server Component payloads for the route segments will be prefetched.
  • If the route is dynamic, the payload from the first shared layout down until the first loading.js file is prefetched. This reduces the cost of prefetching the whole route dynamically and allows instant loading states for dynamic routes.
  • Prefetching is only enabled in production.
  • Prefetching can be disabled by passing prefetch= to .

Soft Navigation

On navigation, the cache for changed segments is reused (if it exists), and no new requests are made to the server for data.

Conditions for Soft Navigation

On navigation, Next.js will use soft navigation if the route you are navigating to has been prefetched, and either doesn’t include dynamic segments or has the same dynamic parameters as the current route.

For example, consider the following route that includes a dynamic [team] segment: /dashboard/[team]/* . The cached segments below /dashboard/[team]/* will only be invalidated when the [team] parameter changes.

  • Navigating from /dashboard/team-red/* to /dashboard/team-red/* will be a soft navigation.
  • Navigating from /dashboard/team-red/* to /dashboard/team-blue/* will be a hard navigation.

Hard Navigation

On navigation, the cache is invalidated and the server refetches data and re-renders the changed segments.

Back/Forward Navigation

Back and forward navigation (popstate event

) has a soft navigation behavior. This means, the client-side cache is re-used and navigation is near-instant.

Focus and Scroll Management

By default, Next.js will set focus and scroll into view the segment that’s changed on navigation.

Источник

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The navigate() method of the Navigation interface navigates to a specific URL, updating any provided state in the history entries list.

Syntax

navigate(url) navigate(url, options) 

Parameters

The destination URL to navigate to. Note that when calling navigate() on a another window’s navigation object, the URL will be resolved relative to the target window’s URL, not the calling window’s URL. This matches the behavior of the History API, but not the behavior of the Location API.

An options object containing the following properties:

Developer-defined information to be stored in the associated NavigationHistoryEntry once the navigation is complete, retrievable via getState() . This can be any data type. You might, for example, wish to store a page visit count for analytics purposes, or store UI state details so the view can be shown exactly as the user last left it. Any data stored in state must be structured-cloneable.

Developer-defined information to be passed along to the navigate event, made available in NavigateEvent.info . This can be any data type. You might, for example, wish to display newly-navigated content with a different animation depending on how it was navigated to (swipe left, swipe right, or go home). A string indicating which animation to use could be passed in as info .

An enumerated value that sets the history behavior of this navigation. The available values are:

  • auto : The default value; will usually perform a push navigation but will perform a replace navigation under special circumstances (see the NotSupportedError description below).
  • push : Will push a new NavigationHistoryEntry onto the entries list, or fail under special circumstances (see the NotSupportedError description below).
  • replace : Will replace the current NavigationHistoryEntry .

Return value

An object with the following properties:

A Promise which will fulfill when the visible URL has changed and a new NavigationHistoryEntry has been created.

A Promise which will fulfill when all promises returned by the intercept() handler are fulfilled. This is equivalent to the NavigationTransition.finished promise fulfilling, when the navigatesuccess event fires.

Either one of these promises rejects if the navigation has failed for some reason.

Exceptions

Thrown if the state parameter had values included in it that are not structured-cloneable.

Thrown if the url parameter is not a valid URL.

Thrown if the history option is set to push , and any of the following special circumstances are true:

  • The browser is currently showing the initial about:blank document.
  • The url ‘s scheme is javascript .

Examples

Set up home button

function initHomeBtn()  // Get the key of the first loaded entry // so the user can always go back to this view. const  key > = navigation.currentEntry; backToHomeButton.onclick = () =>  navigation.traverseTo(key); >; > // Intercept navigate events, such as link clicks, and // replace them with single-page navigations navigation.addEventListener("navigate", (event) =>  event.intercept( async handler()  // Navigate to a different view, // but the "home" button will always work. >, >); >); 

A smart back button

A page-supplied «back» button can take you back, even after reload, by inspecting the previous history entries:

.addEventListener("click", () =>  if ( navigation.entries()[navigation.currentEntry.index - 1]?.url === "/product-listing" )  navigation.back(); > else  // If the user arrived here in some other way // e.g. by typing the URL directly: navigation.navigate("/product-listing",  history: "replace" >); > >); 

Using info and state

async function navigateHandler()  await navigation.navigate(url,  info:  animation: "swipe-right" >, state:  infoPaneOpen: true >, >); > 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 13, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Читайте также:  Test1 ru install php
Оцените статью