From b2df2cff26c6baf5091908d74a400d05097a4255 Mon Sep 17 00:00:00 2001 From: Josh Slate Date: Thu, 1 Dec 2022 04:21:57 -0800 Subject: [PATCH] chore(examples): Update active-class-name example (#43581) I updated the `active-class-name` example to stop using the legacy behavior. ## Documentation / Examples - [x] Make sure the linting passes by running `pnpm build && pnpm lint` - [x] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md) --- .../components/ActiveLink.tsx | 29 ++++++++----------- examples/active-class-name/components/Nav.tsx | 21 +++++++++----- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/examples/active-class-name/components/ActiveLink.tsx b/examples/active-class-name/components/ActiveLink.tsx index c9501b52f951d..5745eff025462 100644 --- a/examples/active-class-name/components/ActiveLink.tsx +++ b/examples/active-class-name/components/ActiveLink.tsx @@ -1,22 +1,20 @@ import { useRouter } from 'next/router' import Link, { LinkProps } from 'next/link' -import React, { useState, useEffect, ReactElement, Children } from 'react' +import React, { PropsWithChildren, useState, useEffect } from 'react' type ActiveLinkProps = LinkProps & { - children: ReactElement + className?: string activeClassName: string } const ActiveLink = ({ children, activeClassName, + className, ...props -}: ActiveLinkProps) => { +}: PropsWithChildren) => { const { asPath, isReady } = useRouter() - - const child = Children.only(children) - const childClassName = child.props.className || '' - const [className, setClassName] = useState(childClassName) + const [computedClassName, setComputedClassName] = useState(className) useEffect(() => { // Check if the router fields are updated client-side @@ -33,11 +31,11 @@ const ActiveLink = ({ const newClassName = linkPathname === activePathname - ? `${childClassName} ${activeClassName}`.trim() - : childClassName + ? `${className} ${activeClassName}`.trim() + : className - if (newClassName !== className) { - setClassName(newClassName) + if (newClassName !== computedClassName) { + setComputedClassName(newClassName) } } }, [ @@ -45,17 +43,14 @@ const ActiveLink = ({ isReady, props.as, props.href, - childClassName, activeClassName, - setClassName, className, + computedClassName, ]) return ( - - {React.cloneElement(child, { - className: className || null, - })} + + {children} ) } diff --git a/examples/active-class-name/components/Nav.tsx b/examples/active-class-name/components/Nav.tsx index 921cc15120bfd..36afaa4cecd45 100644 --- a/examples/active-class-name/components/Nav.tsx +++ b/examples/active-class-name/components/Nav.tsx @@ -13,23 +13,28 @@ const Nav = () => ( `}