Trung  Nguyen

Trung Nguyen

1598512080

Lập trình NextJs - Solution 05

Video demo được trích từ khóa học Lập trình NextJs tại ZendVN.com

Download souce code tại: https://github.com/luutruonghailan/hoc-lap-trinh-online-zendvn/tree/master/khoa-hoc-nextjs

#next #react

What is GEEK

Buddha Community

Lập trình NextJs - Solution 05

Latest Technology Solution Development - WebClues Infotech

Latest IT Tech Solution Development Company

The technology in the IT sector is rapidly growing with everything in the world moving online to make users life easy with it. This development in technology has allowed critical industries to also move online with technologies like blockchain, Artificial intelligence, Cloud Computing, Big Data Service, etc.

Want to use the latest technologies in IT for your business?

WebClues Infotech with its policy to train employees with the latest technologies like Blockchain, Wearables app, Chatbot app, AI and many more is the leader in the development of those technologies. With a highly-skilled team of 120+ people there can be no better option for your development requirements in the latest techs.

Want to know more about the technologies we provide solutions in?

Visit: https://www.webcluesinfotech.com/latest-technology-development/

Share your requirements https://www.webcluesinfotech.com/contact-us/

View Portfolio https://www.webcluesinfotech.com/portfolio/

#latest it tech solution development company #it tech solution development company #it tech solution #technology solution development #it path solutions #tech solution india

How Do I Pass the AWS Solutions Architect Associate Exam? Careerera

The AWS solutions architect associate exam is one of the most difficult certification exams in the world. There are many certifications for various things such as the PMP certification and the CISSP certification, but it is the AWS solutions architect associate exam which takes the crown when it comes to difficulty.

How to Qualify an AWS Certified Solutions Architect Associate Exam?

Naturally, given the difficulty of the exam many people wonder, “How Do I Pass the AWS Solutions Architect Associate Exam?” on the first attempt. This is a very valid question and, in this article, we will discuss all the ways in which one can maximize his chances of passing the AWS solutions architect associate exam in the first attempt.

Before starting we must remember one thing – the AWS platform is a beast of a platform and is vast beyond comprehension. So, for a beginner looking to take the AWS solutions architect associate exam it will not be possible to cover all the topics and services related to the AWS platform.

However, one can make one’s best attempt to cover all the core concepts and topics which are most relevant and pertinent to the AWS platform. A candidate for the AWS solutions architect associate exam in particular should keep himself updated on all the most recent advances and developments in the field of AWS.

Which services are tested most frequently on the exam?

  1. Amazon EC2 -

This service is used to create virtual machines which are offsite. It is also used to manage things such as ports, security, and storage because of its many features. It allows the users to utilize AWS’ vast computing capabilities on-demand. With a ‘scale as you grow’ philosophy the user is not trapped into an agreement in which they will have to purchase excessive resources from Amazon.
They only have to make use of as many resources as they need. The Amazon EC2 web interface allows the software developers to configure and resize the compute machines to their heart’s content with minimal friction and absolutely no confusion whatsoever. All decent AWS Solutions Architect Associate Certification courses teach how to make use of this service.

  1. Amazon RDS -

The full form of Amazon RDS is Amazon Relational Database Service. It is an extremely useful service launched by Amazon. It is used by software developers to create a database with all the features of a full-fledged offline database in a matter of minutes.

The main purpose of Amazon RDS is to set up relational databases in the cloud. These databases can be set up, operated, and scaled very easily and very smoothly. Amazon provides a very seamless and slick interface which is ideal for operating the databases thus created.

The databases are very cost-effective and can be resized very easily. They provide all facilities to carry out administrative tasks such as hardware provisioning, database setup, patching and backups. With the help of these databases, one will be able to give their applications fast performance, high availability, security and compatibility.

  1. Amazon S3 -

The full form of Amazon S3 is Amazon Simple Storage Service. It is a service which provides a lot of expediency to software developers in the matter of storage. Software developers can create objects through programming and they can then store those objects which they have coded into the Amazon S3 service.

This service is responsible in a large part for having made AWS the leading cloud services provider in the world. Truly Jeff Bezos must have been inspired by a divine vision when he conceived of this service. This service leads the industry in terms of scalability, data availability, security, and performance.

How difficult is the AWS solutions architect associate exam?

As we have mentioned before, the AWS platform is vast beyond comprehension. It contains multitudes of services and all of them have their own various configuration options and switches. This means that for a candidate who is just starting his journey of becoming a AWS certified solution architect associate it is not possible to master the whole platform immediately.

It will take many years and a lot of practical and hands-on experience before he is able to do so. But the AWS solutions architect associate exam has a very extensive syllabus and is thus prohibitively difficult for the candidates. Its syllabus contains the following domains of knowledge -

• Design Resilient Architectures - 34%
• Define Performant Architecture – 24%
• Specify Secure Applications and Architectures – 24%
• Design Cost-Optimized Architectures – 10%
• Define Operationally Excellent Architectures – 8%

Some tips which will help to clear the exam -

  1. Read as many AWS whitepapers as possible -

The AWS whitepapers explain many core concepts of the AWS platform in very technical, precise, and accurate language. For a candidate preparing for the AWS solutions architect associate exam, it is very beneficial to read the whitepapers as they will illuminate many technical and hard to grasp concepts of the AWS platform in a detailed and scientific way.

  1. Make use of the process of elimination for multiple correct answers -

On the AWS solutions architect associate exam there will be many questions which will have multiple options. For those questions the candidate should first try to identify and eliminate the incorrect options so that they have to contemplate a fewer number of options while trying to find the correct answer.

  1. Try to spot questions which have hints and details about other questions -

Many times, there will be questions on the exam which will contain hints and details pertinent to other questions on the exam. So, the candidate should keep a weather eye out for such questions and read all questions carefully with this aspect of the exam kept in mind firmly. This trick is taught in many AWS Solutions Architect Associate Certification courses.

  1. Take an AWS solution architect associate course -

The best way to pass the AWS solutions architect associate exam is to take an AWS solution architect associate course. This will help the candidate because they will be studying under the guidance of seasoned and experienced instructors who will be able to bring their world-class teaching skills and subject matter expertise to bear to make the learners fully prepared for the exam.

#how do i pass the aws solutions architect associate exam #how to qualify an aws certified solutions architect associate exam #aws solutions architect associate exam #aws solutions architect associate certification courses #aws certified solution architect associate #aws solution architect associate course

Implement a Dynamic Breadcrumb in React/NextJS

 Breadcrumbs are a website navigation tool that allows a user to see their current page's "stack" of how it is nested under any parent pages. Users can then jump back to a parent page by clicking the associated breadcrumb link. These "Crumbs" increase the User Experience of the application, making it easier for the users to navigate nested pages efficiently and effectively.

 

Example Breadcrumbs

Breadcrumbs are popular enough that if you are building a web dashboard or application, you may have considered adding them. Generating these breadcrumb links efficiently and with the appropriate context is key to an improved user experience.

Let's build a smart NextBreadcrumbs React component that will parse the current route and build a dynamic breadcrumbs display that can handle both static & dynamic routes efficiently.

My projects usually revolve around Nextjs and MUI (formerly Material-UI) so that is the angle that I am going to approach this problem from, although the solution should work for any Nextjs-related application.

#Static Route Breadcrumbs

To start, our NextBreadcrumbs component will only handle static routes, meaning that our project has only static pages defined in the pages directory.

The following are examples of static routes because they do not contain [s and ]s in the route names, meaning the directory structure lines up 1:1 exactly with the expected URLs that they serve.

  • pages/index.js --> /
  • pages/about.js --> /about
  • pages/my/super/nested/route.js --> /my/super/nested/route

The solution will be extended to handle dynamic routes later.

#Defining the Basic Component

We can start with the basic component that uses the MUI Breadcrumbs component as a baseline.

import Breadcrumbs from '@mui/material/Breadcrumbs';
import * as React from 'react';

export default function NextBreadcrumbs() {
  return (
    <Breadcrumbs aria-label="breadcrumb" />
  );
}

The above creates the basic structure of the NextBreadcrumbs React component, imports the correct dependencies, and renders an empty Breadcrumbs MUI component.

We can then add in the next/router hooks, which will allow us to build the breadcrumbs from the current route.

We also create a Crumb component that will be used to render each link. This is a pretty dumb component for now, except that it will render normal text instead of a link for the last breadcrumb.

In a situation like /settings/notifications, it would render as the following:

Home (/ link) > Settings (/settings link) > Notifications (no link)

This is because the user is already on the last breadcrumb's page, so there is no need to link out to the same page. All the other crumbs are rendered as links to be clicked.

import Breadcrumbs from '@mui/material/Breadcrumbs';
import Link from '@mui/material/Link';
import Typography from '@mui/material/Typography';
import { useRouter } from 'next/router';
import React from 'react';


export default function NextBreadcrumbs() {
  // Gives us ability to load the current route details
  const router = useRouter();
  
  return (
    <Breadcrumbs aria-label="breadcrumb" />
  );
}


// Each individual "crumb" in the breadcrumbs list
function Crumb({ text, href, last=false }) {
  // The last crumb is rendered as normal text since we are already on the page
  if (last) {
  	return <Typography color="text.primary">{text}</Typography>
  }

  // All other crumbs will be rendered as links that can be visited 
  return (
    <Link underline="hover" color="inherit" href={href}>
      {text}
    </Link>
  );
}

With this layout, we can then dive back into the NextBreadcrumbs component to generate the breadcrumbs from the route. Some existing code will start to be omitted to keep the code pieces smaller. The full example is shown below.

We will generate a list of breadcrumb objects that contain the information to be rendered by each Crumb element. Each breadcrumb will be created by parsing the Nextjs router's asPath property, which is a string containing the route as shown in the browser URL bar.

We will strip any query parameters, such as ?query=value, from the URL to make the breadcrumb creation process more straightforward.

export default function NextBreadcrumbs() {
  // Gives us ability to load the current route details
  const router = useRouter();
  
  function generateBreadcrumbs() {
    // Remove any query parameters, as those aren't included in breadcrumbs
    const asPathWithoutQuery = router.asPath.split("?")[0];
	
	// Break down the path between "/"s, removing empty entities
	// Ex:"/my/nested/path" --> ["my", "nested", "path"]
	const asPathNestedRoutes = asPathWithoutQuery.split("/")
												 .filter(v => v.length > 0);
	
	// Iterate over the list of nested route parts and build
	// a "crumb" object for each one.
	const crumblist = asPathParts.map((subpath, idx) => {
	  // We can get the partial nested route for the crumb
	  // by joining together the path parts up to this point.
	  const href = "/" + asPathNestedRoutes.slice(0, idx + 1).join("/");
	  // The title will just be the route string for now
	  const title = subpath;
  	  return { href, text }; 
    })
	
	// Add in a default "Home" crumb for the top-level
	return [{ href: "/", text: "Home" }, ...crumblist];
  }
  
  // Call the function to generate the breadcrumbs list
  const breadcrumbs = generateBreadcrumbs();
  
  return (
    <Breadcrumbs aria-label="breadcrumb" />
  );
}

With this list of breadcrumbs, we can now render them using the Breadcrumbs and Crumb components. As previously mentioned, only the return portion of our component is shown for brevity.

  // ...rest of NextBreadcrumbs component above...
  return (
    {/* The old breadcrumb ending with '/>' was converted into this */}
    <Breadcrumbs aria-label="breadcrumb">
	  {/*
	    Iterate through the crumbs, and render each individually.
		We "mark" the last crumb to not have a link.
      */}
	  {breadcrumbs.map((crumb, idx) => (
	    <Crumb {...crumb} key={idx} last={idx === breadcrumbs.length - 1} />
	  ))}
	</Breadcrumbs>
  );

This should start generating some very basic - but working - breadcrumbs on our site once rendered; /user/settings/notifications would render as

Home > user > settings > notifications

#Memoizing Generated Breadcrumbs

There is a quick improvement that we can make before going further though. Right now the breadcrumb list is recreated every time the component re-renders, so we can memoize the crumb list for a given route to save some performance. To accomplish this, we can wrap our generateBreadcrumbs function call in the useMemo React hook.

  const router = useRouter();
  
  // this is the same "generateBreadcrumbs" function, but placed
  // inside a "useMemo" call that is dependent on "router.asPath"
  const breadcrumbs = React.useMemo(function generateBreadcrumbs() {
    const asPathWithoutQuery = router.asPath.split("?")[0];
	const asPathNestedRoutes = asPathWithoutQuery.split("/")
												 .filter(v => v.length > 0);

	const crumblist = asPathParts.map((subpath, idx) => {
	  const href = "/" + asPathNestedRoutes.slice(0, idx + 1).join("/");
  	  return { href, text: subpath }; 
    })
	
	return [{ href: "/", text: "Home" }, ...crumblist];
  }, [router.asPath]);
  
  return // ...rest below...

#Improving Breadcrumb Text Display

Before we start incorporating dynamic routes, we can clean this current solution up more by including a nice way to change the text shown for each crumb generated.

Right now, if we have a path like /user/settings/notifications, then it will show:

Home > user > settings > notifications

which is not very appealing. We can provide a function to the NextBreadcrumbs component that will try to generate a more user-friendly name for each of these nested route crumbs.


const _defaultGetDefaultTextGenerator= path => path

export default function NextBreadcrumbs({ getDefaultTextGenerator=_defaultGetDefaultTextGenerator }) {
  const router = useRouter();

  // Two things of importance:
  // 1. The addition of getDefaultTextGenerator in the useMemo dependency list
  // 2. getDefaultTextGenerator is now being used for building the text property
  const breadcrumbs = React.useMemo(function generateBreadcrumbs() {
    const asPathWithoutQuery = router.asPath.split("?")[0];
	const asPathNestedRoutes = asPathWithoutQuery.split("/")
												 .filter(v => v.length > 0);

	const crumblist = asPathParts.map((subpath, idx) => {
	  const href = "/" + asPathNestedRoutes.slice(0, idx + 1).join("/");
  	  return { href, text: getDefaultTextGenerator(subpath, href) }; 
    })

	return [{ href: "/", text: "Home" }, ...crumblist];
  }, [router.asPath, getDefaultTextGenerator]);
  
  return ( // ...rest below

and then our parent component can have something like the following, to title-ize the subpaths, or maybe even replace them with a new string.

{/* Assume that `titleize` is written and works appropriately */}
<NextBreadcrumbs getDefaultTextGenerator={path => titleize(path)} />

This implementation would then result in the following breadcrumbs. The full code example at the bottom has more examples of this.

Home > User > Settings > Notifications

#Nextjs Dynamic Routes

Nextjs's router allows for including dynamic routes that uses Pattern Matching to allow for URLs to have slugs, UUIDs, and other dynamic values that will then be passed to your views.

For example, if your Nextjs application has a page component at pages/post/[post_id].js, then the routes /post/1 and /post/abc will match it.

For our breadcrumbs component, we would like to show the name of the associated post instead of just its UUID. This means that the component will need to dynamically look up the post data based on the nested URL route path and regenerate the text of the associated crumb.

Right now, if you visit /post/abc, you would see breadcrumbs that look like

post > abc

but if the post with UUID has a title of My First Post, then we want to change the breadcrumbs to say

post > My First Post

Let's dive into how that can happen using async functions.

#Nextjs Router: asPath vs pathname

The next/router router instance in our code has two useful properties for our NextBreadcrumbs component; asPath and pathname. The router asPath is the URL path as shown directly in the URL bar of the browser. The pathname is a more internal version of the URL that has the dynamic parts of the path replaced with their [parameter] components.

For example, consider the path /post/abc from above.

The asPath would be /post/abc as the URL is shown

The pathname would be /post/[post_id] as our pages directory dictates

We can use these two URL path variants to build a way to dynamically fetch information about the breadcrumb, so we can show more contextually appropriate information to the user.

There is a lot going on below, so please re-read it - and the helpful notes below it - a few times over if needed.


const _defaultGetTextGenerator = (param, query) => null;
const _defaultGetDefaultTextGenerator = path => path;

// Pulled out the path part breakdown because its
// going to be used by both `asPath` and `pathname`
const generatePathParts = pathStr => {
  const pathWithoutQuery = pathStr.split("?")[0];
  return pathWithoutQuery.split("/")
						 .filter(v => v.length > 0);
}

export default function NextBreadcrumbs({
  getTextGenerator=_defaultGetTextGenerator,
  getDefaultTextGenerator=_defaultGetDefaultTextGenerator
}) {
  const router = useRouter();

  const breadcrumbs = React.useMemo(function generateBreadcrumbs() {
    const asPathNestedRoutes = generatePathParts(router.asPath);
	const pathnameNestedRoutes = generatePathParts(router.pathname);

	const crumblist = asPathParts.map((subpath, idx) => {
	  // Pull out and convert "[post_id]" into "post_id"
	  const param = pathnameNestedRoutes[idx].replace("[", "").replace("]", "");

	  const href = "/" + asPathNestedRoutes.slice(0, idx + 1).join("/");
  	  return {
	  	href, textGenerator: getTextGenerator(param, router.query),
		text: getDefaultTextGenerator(subpath, href)
	  }; 
    })

	return [{ href: "/", text: "Home" }, ...crumblist];
  }, [router.asPath, router.pathname, router.query, getTextGenerator, getDefaultTextGenerator]);
  
  return ( // ...rest below

The asPath breakdown was moved to a generatePathParts function since the same logic is used for both router.asPath and router.pathname.

Determine the parameter that lines up with the dynamic route value, so abc would result in post_id.

The nested route parameter and all associated query values (router.query) are passed to a provided getTextGenerator which will return either a null value or a Promise response that should return the dynamic string to use in the associated breadcrumb.

The useMemo dependency array has more dependencies added; router.pathname, router.query, and getTextGenerator.

Finally, we need to update the Crumb component to use this textGenerator value if it is provided for the associated crumb object.

function Crumb({ text: defaultText, textGenerator, href, last=false }) {

  const [text, setText] = React.useState(defaultText);
  
  useEffect(async () => {
    // If `textGenerator` is nonexistent, then don't do anything
    if (!Boolean(textGenerator)) { return; }
	// Run the text generator and set the text again
    const finalText = await textGenerator();
    setText(finalText);
  }, [textGenerator]);

  if (last) {
  	return <Typography color="text.primary">{text}</Typography>
  }

  return (
    <Link underline="hover" color="inherit" href={href}>
      {text}
    </Link>
  );
}

 

The breadcrumbs can now handle both static routes and dynamic routes cleanly with the potential to display user-friendly values. While the above code is the business logic of the component, this can all be used with a parent component that looks like the final example below.

#Full Example

// NextBreadcrumbs.js

const _defaultGetTextGenerator = (param, query) => null;
const _defaultGetDefaultTextGenerator = path => path;

// Pulled out the path part breakdown because its
// going to be used by both `asPath` and `pathname`
const generatePathParts = pathStr => {
  const pathWithoutQuery = pathStr.split("?")[0];
  return pathWithoutQuery.split("/")
						 .filter(v => v.length > 0);
}

export default function NextBreadcrumbs({
  getTextGenerator=_defaultGetTextGenerator,
  getDefaultTextGenerator=_defaultGetDefaultTextGenerator
}) {
  const router = useRouter();

  const breadcrumbs = React.useMemo(function generateBreadcrumbs() {
    const asPathNestedRoutes = generatePathParts(router.asPath);
	const pathnameNestedRoutes = generatePathParts(router.pathname);

	const crumblist = asPathParts.map((subpath, idx) => {
	  // Pull out and convert "[post_id]" into "post_id"
	  const param = pathnameNestedRoutes[idx].replace("[", "").replace("]", "");

	  const href = "/" + asPathNestedRoutes.slice(0, idx + 1).join("/");
  	  return {
	  	href, textGenerator: getTextGenerator(param, router.query),
		text: getDefaultTextGenerator(subpath, href)
	  }; 
    })

	return [{ href: "/", text: "Home" }, ...crumblist];
  }, [router.asPath, router.pathname, router.query, getTextGenerator, getDefaultTextGenerator]);
  
  return (
    <Breadcrumbs aria-label="breadcrumb">
	  {breadcrumbs.map((crumb, idx) => (
	    <Crumb {...crumb} key={idx} last={idx === breadcrumbs.length - 1} />
	  ))}
	</Breadcrumbs>
  );
}


function Crumb({ text: defaultText, textGenerator, href, last=false }) {

  const [text, setText] = React.useState(defaultText);
  
  useEffect(async () => {
    // If `textGenerator` is nonexistent, then don't do anything
    if (!Boolean(textGenerator)) { return; }
	// Run the text generator and set the text again
    const finalText = await textGenerator();
    setText(finalText);
  }, [textGenerator]);

  if (last) {
  	return <Typography color="text.primary">{text}</Typography>
  }

  return (
    <Link underline="hover" color="inherit" href={href}>
      {text}
    </Link>
  );
}

and then an example of this NextBreadcrumbs being used can be seen below. Note that useCallback is used to create only one reference to each helper function which will prevent unnecessary re-renders of the breadcrumbs when/if the page layout component re-rendered. You could also move this out to the top-level scope of the file, but I don't like to pollute the global scope like that.

// MyPage.js (Parent Component)

import React from 'react';
import NextBreadcrumbs from "./NextBreadcrumbs";


function MyPageLayout() {

  // Either lookup a nice label for the subpath, or just titleize it
  const getDefaultTextGenerator = React.useCallback((subpath) => {
    return {
	  "post": "Posts",
	  "settings": "User Settings",
	}[subpath] || titleize(subpath);
  }, [])
  
  // Assuming `fetchAPI` loads data from the API and this will use the
  // parameter name to determine how to resolve the text. In the example,
  // we fetch the post from the API and return it's `title` property
  const getTextGenerator = React.useCallback((param, query) => {
    return {
	  "post_id": () => await fetchAPI(`/posts/${query.post_id}/`).title,
	}[param];
  }, []);

  return () {
    <div>
	  {/* ...Whatever else... */}
	  <NextBreadcrumbs
	    getDefaultTextGenerator={getDefaultTextGenerator}
		getTextGenerator={getTextGenerator}
	  />
	  {/* ...Whatever else... */}
	</div>
  }

}

This is one of my more in-depth and technical posts, so I hope you enjoyed it, and please comment or reach out so that I can ensure consistency and correctness. Hopefully, this post taught you a few strategies or concepts about Nextjs.

Source: https://hackernoon.com/implement-a-dynamic-breadcrumb-in-reactnextjs

#react #nextjs 

Diego  Elizondo

Diego Elizondo

1652517446

Implementar Una Ruta De Navegación Dinámica En React/NextJS

Las migas de pan son una herramienta de navegación del sitio web que permite a un usuario ver la "pila" de su página actual de cómo está anidada debajo de las páginas principales. Luego, los usuarios pueden regresar a una página principal haciendo clic en el enlace de ruta de navegación asociado. Estas "migajas" aumentan la experiencia del usuario de la aplicación, lo que facilita que los usuarios naveguen por páginas anidadas de manera eficiente y efectiva.

 

Ejemplo de migas de pan

Las migas de pan son lo suficientemente populares como para que, si está creando un panel de control web o una aplicación, haya considerado agregarlas. Generar estos enlaces de migas de pan de manera eficiente y con el contexto apropiado es clave para una experiencia de usuario mejorada.

Construyamos un NextBreadcrumbs componente React inteligente que analice la ruta actual y construya una pantalla de migas de pan dinámicas que pueda manejar rutas tanto estáticas como dinámicas de manera eficiente.

Mis proyectos generalmente giran en torno a Nextjs y MUI (anteriormente Material-UI), por lo que ese es el ángulo desde el que abordaré este problema, aunque la solución debería funcionar para cualquier aplicación relacionada con Nextjs.

#Breadcrumbs de ruta estática

Para empezar, nuestro NextBreadcrumbscomponente solo manejará rutas estáticas, lo que significa que nuestro proyecto solo tiene páginas estáticas definidas en el pagesdirectorio.

Los siguientes son ejemplos de rutas estáticas porque no contienen [s y ]s en los nombres de ruta, lo que significa que la estructura del directorio se alinea 1:1 exactamente con las URL esperadas que sirven.

  • pages/index.js-->/
  • pages/about.js-->/about
  • pages/my/super/nested/route.js-->/my/super/nested/route

La solución se ampliará para manejar rutas dinámicas más adelante.

#Definiendo el Componente Básico

Podemos comenzar con el componente básico que usa el componente MUIBreadcrumbs como línea de base.

import Breadcrumbs from '@mui/material/Breadcrumbs';
import * as React from 'react';

export default function NextBreadcrumbs() {
  return (
    <Breadcrumbs aria-label="breadcrumb" />
  );
}

Lo anterior crea la estructura básica del NextBreadcrumbscomponente React, importa las dependencias correctas y genera un Breadcrumbscomponente MUI vacío.

Luego podemos agregar los next/routerganchos, lo que nos permitirá construir las migas de pan a partir de la ruta actual.

También creamos un Crumbcomponente que se usará para representar cada enlace. Este es un componente bastante tonto por ahora, excepto que mostrará texto normal en lugar de un enlace para la última ruta de navegación.

En una situación como /settings/notifications, se representaría de la siguiente manera:

Home (/ link) > Settings (/settings link) > Notifications (no link)

Esto se debe a que el usuario ya está en la última página de migas de pan, por lo que no es necesario vincular a la misma página. Todas las demás migajas se representan como enlaces en los que se puede hacer clic.

import Breadcrumbs from '@mui/material/Breadcrumbs';
import Link from '@mui/material/Link';
import Typography from '@mui/material/Typography';
import { useRouter } from 'next/router';
import React from 'react';


export default function NextBreadcrumbs() {
  // Gives us ability to load the current route details
  const router = useRouter();
  
  return (
    <Breadcrumbs aria-label="breadcrumb" />
  );
}


// Each individual "crumb" in the breadcrumbs list
function Crumb({ text, href, last=false }) {
  // The last crumb is rendered as normal text since we are already on the page
  if (last) {
  	return <Typography color="text.primary">{text}</Typography>
  }

  // All other crumbs will be rendered as links that can be visited 
  return (
    <Link underline="hover" color="inherit" href={href}>
      {text}
    </Link>
  );
}

Con este diseño, podemos volver a sumergirnos en el NextBreadcrumbscomponente para generar las migas de pan a partir de la ruta. Parte del código existente comenzará a omitirse para mantener las piezas de código más pequeñas. El ejemplo completo se muestra a continuación.

Generaremos una lista de objetos de migas de pan que contienen la información que cada Crumbelemento debe representar. Cada ruta de navegación se creará analizando la propiedad del enrutador NextjsasPath , que es una cadena que contiene la ruta como se muestra en la barra de URL del navegador.

Quitaremos todos los parámetros de consulta, como ?query=value, de la URL para que el proceso de creación de la ruta de navegación sea más sencillo.

export default function NextBreadcrumbs() {
  // Gives us ability to load the current route details
  const router = useRouter();
  
  function generateBreadcrumbs() {
    // Remove any query parameters, as those aren't included in breadcrumbs
    const asPathWithoutQuery = router.asPath.split("?")[0];
	
	// Break down the path between "/"s, removing empty entities
	// Ex:"/my/nested/path" --> ["my", "nested", "path"]
	const asPathNestedRoutes = asPathWithoutQuery.split("/")
												 .filter(v => v.length > 0);
	
	// Iterate over the list of nested route parts and build
	// a "crumb" object for each one.
	const crumblist = asPathParts.map((subpath, idx) => {
	  // We can get the partial nested route for the crumb
	  // by joining together the path parts up to this point.
	  const href = "/" + asPathNestedRoutes.slice(0, idx + 1).join("/");
	  // The title will just be the route string for now
	  const title = subpath;
  	  return { href, text }; 
    })
	
	// Add in a default "Home" crumb for the top-level
	return [{ href: "/", text: "Home" }, ...crumblist];
  }
  
  // Call the function to generate the breadcrumbs list
  const breadcrumbs = generateBreadcrumbs();
  
  return (
    <Breadcrumbs aria-label="breadcrumb" />
  );
}

Con esta lista de migas de pan, ahora podemos renderizarlas usando los componentes Breadcrumbsy . CrumbComo se mencionó anteriormente, solo returnse muestra la parte de nuestro componente por brevedad.

  // ...rest of NextBreadcrumbs component above...
  return (
    {/* The old breadcrumb ending with '/>' was converted into this */}
    <Breadcrumbs aria-label="breadcrumb">
	  {/*
	    Iterate through the crumbs, and render each individually.
		We "mark" the last crumb to not have a link.
      */}
	  {breadcrumbs.map((crumb, idx) => (
	    <Crumb {...crumb} key={idx} last={idx === breadcrumbs.length - 1} />
	  ))}
	</Breadcrumbs>
  );

Esto debería comenzar a generar algunas migas de pan muy básicas, pero que funcionan, en nuestro sitio una vez renderizado; /user/settings/notificationsrepresentaría como

Home > user > settings > notifications

#Memoizing Breadcrumbs generados

Sin embargo, hay una mejora rápida que podemos hacer antes de seguir adelante. En este momento, la lista de migas de pan se recrea cada vez que el componente se vuelve a renderizar, por lo que podemos memorizar la lista de migas de una ruta determinada para ahorrar algo de rendimiento. Para lograr esto, podemos envolver nuestra generateBreadcrumbsllamada de función en el useMemogancho React.

  const router = useRouter();
  
  // this is the same "generateBreadcrumbs" function, but placed
  // inside a "useMemo" call that is dependent on "router.asPath"
  const breadcrumbs = React.useMemo(function generateBreadcrumbs() {
    const asPathWithoutQuery = router.asPath.split("?")[0];
	const asPathNestedRoutes = asPathWithoutQuery.split("/")
												 .filter(v => v.length > 0);

	const crumblist = asPathParts.map((subpath, idx) => {
	  const href = "/" + asPathNestedRoutes.slice(0, idx + 1).join("/");
  	  return { href, text: subpath }; 
    })
	
	return [{ href: "/", text: "Home" }, ...crumblist];
  }, [router.asPath]);
  
  return // ...rest below...

#Mejora de la visualización del texto de la ruta de navegación

Antes de comenzar a incorporar rutas dinámicas, podemos limpiar más esta solución actual al incluir una forma agradable de cambiar el texto que se muestra para cada migaja generada.

En este momento, si tenemos una ruta como /user/settings/notifications, se mostrará:

Home > user > settings > notifications

que no es muy atractivo. Podemos proporcionar una función al NextBreadcrumbscomponente que intentará generar un nombre más fácil de usar para cada uno de estos fragmentos de ruta anidados.


const _defaultGetDefaultTextGenerator= path => path

export default function NextBreadcrumbs({ getDefaultTextGenerator=_defaultGetDefaultTextGenerator }) {
  const router = useRouter();

  // Two things of importance:
  // 1. The addition of getDefaultTextGenerator in the useMemo dependency list
  // 2. getDefaultTextGenerator is now being used for building the text property
  const breadcrumbs = React.useMemo(function generateBreadcrumbs() {
    const asPathWithoutQuery = router.asPath.split("?")[0];
	const asPathNestedRoutes = asPathWithoutQuery.split("/")
												 .filter(v => v.length > 0);

	const crumblist = asPathParts.map((subpath, idx) => {
	  const href = "/" + asPathNestedRoutes.slice(0, idx + 1).join("/");
  	  return { href, text: getDefaultTextGenerator(subpath, href) }; 
    })

	return [{ href: "/", text: "Home" }, ...crumblist];
  }, [router.asPath, getDefaultTextGenerator]);
  
  return ( // ...rest below

y luego nuestro componente principal puede tener algo como lo siguiente, para titular las rutas secundarias, o tal vez incluso reemplazarlas con una nueva cadena.

{/* Assume that `titleize` is written and works appropriately */}
<NextBreadcrumbs getDefaultTextGenerator={path => titleize(path)} />

Esta implementación daría como resultado las siguientes migas de pan. El ejemplo de código completo en la parte inferior tiene más ejemplos de esto.

Home > User > Settings > Notifications

#Nextjs Rutas dinámicas

El enrutador de Nextjs permite incluir rutas dinámicas que usan Pattern Matching para permitir que las URL tengan slugs, UUID y otros valores dinámicos que luego se pasarán a sus vistas.

Por ejemplo, si su aplicación Nextjs tiene un componente de página en pages/post/[post_id].js, las rutas /post/1y /post/abccoincidirán con él.

Para nuestro componente de migas de pan, nos gustaría mostrar el nombre de la publicación asociada en lugar de solo su UUID. Esto significa que el componente deberá buscar dinámicamente los datos de la publicación en función de la ruta de la ruta URL anidada y regenerar el texto de la migaja asociada.

En este momento, si visitas /post/abc, verás migas de pan que parecen

post > abc

pero si la publicación con UUID tiene un título de My First Post, entonces queremos cambiar las migas de pan para decir

post > My First Post

Profundicemos en cómo puede suceder eso usando asyncfunciones.

Enrutador #Nextjs: asPathvspathname

La next/routerinstancia del enrutador en nuestro código tiene dos propiedades útiles para nuestro NextBreadcrumbscomponente; asPathy pathname. El enrutador asPathes la ruta URL como se muestra directamente en la barra de URL del navegador. Es pathnameuna versión más interna de la URL que tiene las partes dinámicas de la ruta reemplazadas por sus [parameter]componentes.

Por ejemplo, considere el camino /post/abcdesde arriba.

El asPathsería /post/abccomo se muestra la URL

El pathnamesería como dicta /post/[post_id]nuestro directoriopages

Podemos usar estas dos variantes de ruta de URL para crear una forma de obtener información dinámicamente sobre la ruta de navegación, de modo que podamos mostrar información contextualmente más apropiada para el usuario.

Están sucediendo muchas cosas a continuación, así que vuelva a leerlo, y las notas útiles a continuación, unas cuantas veces si es necesario.


const _defaultGetTextGenerator = (param, query) => null;
const _defaultGetDefaultTextGenerator = path => path;

// Pulled out the path part breakdown because its
// going to be used by both `asPath` and `pathname`
const generatePathParts = pathStr => {
  const pathWithoutQuery = pathStr.split("?")[0];
  return pathWithoutQuery.split("/")
						 .filter(v => v.length > 0);
}

export default function NextBreadcrumbs({
  getTextGenerator=_defaultGetTextGenerator,
  getDefaultTextGenerator=_defaultGetDefaultTextGenerator
}) {
  const router = useRouter();

  const breadcrumbs = React.useMemo(function generateBreadcrumbs() {
    const asPathNestedRoutes = generatePathParts(router.asPath);
	const pathnameNestedRoutes = generatePathParts(router.pathname);

	const crumblist = asPathParts.map((subpath, idx) => {
	  // Pull out and convert "[post_id]" into "post_id"
	  const param = pathnameNestedRoutes[idx].replace("[", "").replace("]", "");

	  const href = "/" + asPathNestedRoutes.slice(0, idx + 1).join("/");
  	  return {
	  	href, textGenerator: getTextGenerator(param, router.query),
		text: getDefaultTextGenerator(subpath, href)
	  }; 
    })

	return [{ href: "/", text: "Home" }, ...crumblist];
  }, [router.asPath, router.pathname, router.query, getTextGenerator, getDefaultTextGenerator]);
  
  return ( // ...rest below

El asPathdesglose se movió a una generatePathPartsfunción ya que se usa la misma lógica para ambos router.asPathy router.pathname.

Determine el paraméter que se alinea con el valor de la ruta dinámica, por lo que abcdaría como resultado post_id.

El éter de ruta anidado paramy todos los valores de consulta asociados ( router.query) se pasan a un proveedor getTextGeneratorque devolverá un nullvalor o una Promiserespuesta que debería devolver la cadena dinámica para usar en la ruta de navegación asociada.

La useMemomatriz de dependencia tiene más dependencias agregadas; router.pathname, router.queryy getTextGenerator.

Finalmente, necesitamos actualizar el Crumbcomponente para usar este textGeneratorvalor si se proporciona para el objeto migas asociado.

function Crumb({ text: defaultText, textGenerator, href, last=false }) {

  const [text, setText] = React.useState(defaultText);
  
  useEffect(async () => {
    // If `textGenerator` is nonexistent, then don't do anything
    if (!Boolean(textGenerator)) { return; }
	// Run the text generator and set the text again
    const finalText = await textGenerator();
    setText(finalText);
  }, [textGenerator]);

  if (last) {
  	return <Typography color="text.primary">{text}</Typography>
  }

  return (
    <Link underline="hover" color="inherit" href={href}>
      {text}
    </Link>
  );
}

 

Las migas de pan ahora pueden manejar rutas estáticas y rutas dinámicas de forma limpia con el potencial de mostrar valores fáciles de usar. Si bien el código anterior es la lógica comercial del componente, todo esto se puede usar con un componente principal que se parece al ejemplo final a continuación.

#Ejemplo Completo

// NextBreadcrumbs.js

const _defaultGetTextGenerator = (param, query) => null;
const _defaultGetDefaultTextGenerator = path => path;

// Pulled out the path part breakdown because its
// going to be used by both `asPath` and `pathname`
const generatePathParts = pathStr => {
  const pathWithoutQuery = pathStr.split("?")[0];
  return pathWithoutQuery.split("/")
						 .filter(v => v.length > 0);
}

export default function NextBreadcrumbs({
  getTextGenerator=_defaultGetTextGenerator,
  getDefaultTextGenerator=_defaultGetDefaultTextGenerator
}) {
  const router = useRouter();

  const breadcrumbs = React.useMemo(function generateBreadcrumbs() {
    const asPathNestedRoutes = generatePathParts(router.asPath);
	const pathnameNestedRoutes = generatePathParts(router.pathname);

	const crumblist = asPathParts.map((subpath, idx) => {
	  // Pull out and convert "[post_id]" into "post_id"
	  const param = pathnameNestedRoutes[idx].replace("[", "").replace("]", "");

	  const href = "/" + asPathNestedRoutes.slice(0, idx + 1).join("/");
  	  return {
	  	href, textGenerator: getTextGenerator(param, router.query),
		text: getDefaultTextGenerator(subpath, href)
	  }; 
    })

	return [{ href: "/", text: "Home" }, ...crumblist];
  }, [router.asPath, router.pathname, router.query, getTextGenerator, getDefaultTextGenerator]);
  
  return (
    <Breadcrumbs aria-label="breadcrumb">
	  {breadcrumbs.map((crumb, idx) => (
	    <Crumb {...crumb} key={idx} last={idx === breadcrumbs.length - 1} />
	  ))}
	</Breadcrumbs>
  );
}


function Crumb({ text: defaultText, textGenerator, href, last=false }) {

  const [text, setText] = React.useState(defaultText);
  
  useEffect(async () => {
    // If `textGenerator` is nonexistent, then don't do anything
    if (!Boolean(textGenerator)) { return; }
	// Run the text generator and set the text again
    const finalText = await textGenerator();
    setText(finalText);
  }, [textGenerator]);

  if (last) {
  	return <Typography color="text.primary">{text}</Typography>
  }

  return (
    <Link underline="hover" color="inherit" href={href}>
      {text}
    </Link>
  );
}

y luego se puede ver un ejemplo de este NextBreadcrumbsuso a continuación. Tenga en cuenta que useCallbackse utiliza para crear solo una referencia a cada función auxiliar, lo que evitará que se vuelvan a procesar innecesariamente las migas de pan cuando/si el componente de diseño de página se vuelve a procesar. También puede mover esto al alcance de nivel superior del archivo, pero no me gusta contaminar el alcance global de esa manera.

// MyPage.js (Parent Component)

import React from 'react';
import NextBreadcrumbs from "./NextBreadcrumbs";


function MyPageLayout() {

  // Either lookup a nice label for the subpath, or just titleize it
  const getDefaultTextGenerator = React.useCallback((subpath) => {
    return {
	  "post": "Posts",
	  "settings": "User Settings",
	}[subpath] || titleize(subpath);
  }, [])
  
  // Assuming `fetchAPI` loads data from the API and this will use the
  // parameter name to determine how to resolve the text. In the example,
  // we fetch the post from the API and return it's `title` property
  const getTextGenerator = React.useCallback((param, query) => {
    return {
	  "post_id": () => await fetchAPI(`/posts/${query.post_id}/`).title,
	}[param];
  }, []);

  return () {
    <div>
	  {/* ...Whatever else... */}
	  <NextBreadcrumbs
	    getDefaultTextGenerator={getDefaultTextGenerator}
		getTextGenerator={getTextGenerator}
	  />
	  {/* ...Whatever else... */}
	</div>
  }

}

Esta es una de mis publicaciones más profundas y técnicas, así que espero que la hayas disfrutado, y por favor comenta o comunícate para que pueda garantizar la coherencia y la corrección. Con suerte, esta publicación le enseñó algunas estrategias o conceptos sobre Nextjs.

Fuente: https://hackernoon.com/implement-a-dynamic-breadcrumb-in-reactnextjs

#react #nextjs 

aviana farren

aviana farren

1617947902

Obtain a well-suited White Label Crypto Exchange Solution

A White label Crypto exchange solution comprises characteristics sort of a capable matching engine, more noteworthy transaction throughput, committed back-office software, API integration, the acknowledgment of both market and limit orders, the existence of multi-level referral programs, and integration with various payment service providers.

#white label crypto exchange solution #white label crypto exchange solutions #crypto exchange solutions #cryptocurrency exchange solutions