Skip to content

[labs/react] Issues using lit-labs wrappers in Next.js #2951

Closed

Description

@WickyNilliams

Description

I have some react wrappers which i have generated from my lit components. These work great in a pure client-side react app. However when using in a next.js app i hit a number of a problems.

Elliot on slack asked me to raise an issue here. Even though i think some of it is an issue on the next.js side, it might help in tracking your next integration story.

Steps to Reproduce

  1. Write this code
import React from "react";
import dynamic from "next/dynamic";

// @org/react contains lit-labs/react wrappers...

// (1) ts error
const MyInput = dynamic(() => import("@org/react").then(({ Input }) => Input), {
  ssr: false,
});

export const Page = () => {
  const ref = React.useRef();

  // (2) ref issue
  const focusInput = () => ref.current.focus();

  return (
    <>
      <MyInput ref={ref} />
      <button onClick={focusInput}>Click me</button>
    </>
  );
};
  1. See this output...

(1) TS complains about the type of the react wrapper component. To fix this I had to cast to any and then back to my actual type. I created a helper function like:

type ComponentModule = typeof import("@org/react");

function createDynamic<
  K extends keyof ComponentsModule,
  T extends ComponentsModule[K]
>(component: K) {
  return dynamic(
    () => import("@org/react").then((module) => module[component] as any),
    { ssr: false }
  ) as T;
}

const MyInput = createDynamic("Input");

(2) when clicking the button you will get an error because the ref is not pointing to the underlying custom-element as you would expect, but rather (i think) the return type of dynamic.

I was able to work around this by adding some indirection and threading through a ref myself:

type ComponentsModule = typeof import("@org/react")

function createDynamic<
  K extends keyof ComponentsModule, 
  T extends ComponentsModule[K]
>(component: K) {
  const Wrapped = dynamic(
    () =>
      import("@org/react").then(module => {
        const Component = module[component] as any

        // @ts-expect-error innerRef is unknown
        const Wrapped = ({ innerRef, ...props }) => <Component ref={innerRef} {...props} />
        Wrapped.displayName = `Wrapped${component}`

        return Wrapped as any
      }),
    { ssr: false }
  )

  // @ts-expect-error innerRef is unknown
  const Forwarded = React.forwardRef((props, ref) => <Wrapped {...props} innerRef={ref} />)
  Forwarded.displayName = `Forwarded${component}`

  return Forwarded as T
}

const MyInput = createDynamic("Input")

This is of course, horrible. I tried various other combinations of forwardRef and/or custom ref properties, but i coudln't get it to work. I even had to suppress some TS issues.

This got so complex, i had to add next.js specific integration to my react package as it would be very difficult to document these issues in such a way that devs consuming the components would understand. It was easier to just give them something they can import for next.js only

Expected Results

(1) no TS errors
(2) refs should work out of the box

Activity

  1. self-assigned this
    on May 31, 2022
  2. changed the title [-][lit-labs/react] Issues using lit-labs wrappers in Next.js[/-] [+][labs/react] Issues using lit-labs wrappers in Next.js[/+] on Jun 16, 2022
  3. moved this to 📋 Triaged in Lit Project Boardon Jun 16, 2022
  4. taylor-vann commented on Sep 30, 2022

    @taylor-vann
    Contributor

    Hey @WickyNilliams #3163 now exports a type ReactWebComponent that should help TS better understand what's returned from createComponent.

    I'm curious if this helps alleviate type woes in an SSR scenario like NextJS.

    I'd also like to work towards better SSR support for the @lit-labs/react package. So any requests or advice? I'm all ears :)

  5. WickyNilliams commented on Sep 30, 2022

    @WickyNilliams
    ContributorAuthor

    Hey thanks for the ping! I'll check this out when I'm back in work next week 🙏

  6. removed their assignment
    on Mar 22, 2023
  7. jianliao commented on Apr 6, 2023

    @jianliao

    Hi @taylor-vann,

    I came across this issue created by @WickyNilliams and found that my target is similar, but I'm using the latest Next.js canary release and the latest @lit-labs/react. I've created a repository to reproduce the issue and tried two different approaches.

    Approach 1
    Code Reference

    // Attempt - 1
    
    export const SpActionButton = dynamic<ActionButtonPropsType>(
      () =>
        import("./ActionButton").then(({ ActionButton }) => {
          return ActionButton;
        }),
      { ssr: false }
    );

    Approach 2
    Code Reference

    // Attempt - 2
    
    const SpActionButtonInner = dynamic<ActionButtonPropsType>(
      () =>
        import("./ActionButton").then(({ ActionButton }) => {
          return ActionButton;
        }),
      { ssr: false }
    );
    
    export const SpActionButton = forwardRef(
      (
        props: PropsWithChildren<ActionButtonPropsType>,
        innerRef?: Ref<ActionButton>
      ) => <SpActionButtonInner {...props} ref={innerRef} />
    );

    Both solutions have no TypeScript errors, but Approach 2 fails during Next.js static export (aka next build). The problem is that both approaches result in the following runtime warning, and the ref remains null:

    9:106 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
    
    Check the render method of `Home`.
        at LoadableComponent
        at div
        at main
        at Home (webpack-internal:///(app-client)/./app/page.tsx:19:65)
        at ScrollAndFocusHandler (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/layout-router.js:184:9)
        at InnerLayoutRouter (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/layout-router.js:241:11)
        at RedirectErrorBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/redirect-boundary.js:54:9)
        at RedirectBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/redirect-boundary.js:62:11)
        at NotFoundErrorBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/not-found-boundary.js:28:9)
        at NotFoundBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/not-found-boundary.js:35:11)
        at LoadingBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/layout-router.js:354:11)
        at ErrorBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/error-boundary.js:72:11)
        at RenderFromTemplateContext (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/render-from-template-context.js:12:34)
        at OuterLayoutRouter (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/layout-router.js:23:11)
        at sp-theme
        at ReactComponent (webpack-internal:///(app-client)/./node_modules/@lit-labs/react/development/create-component.js:118:13)
        at Theme
        at NoSSR (webpack-internal:///(app-client)/./node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-no-ssr.js:16:11)
        at Suspense
        at LoadableComponent
        at body
        at html
        at RootLayout (webpack-internal:///(app-client)/./app/layout.tsx:12:11)
        at RedirectErrorBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/redirect-boundary.js:54:9)
        at RedirectBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/redirect-boundary.js:62:11)
        at NotFoundErrorBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/not-found-boundary.js:28:9)
        at NotFoundBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/not-found-boundary.js:35:11)
        at ReactDevOverlay (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/react-dev-overlay/internal/ReactDevOverlay.js:61:9)
        at HotReload (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/react-dev-overlay/hot-reloader-client.js:20:11)
        at Router (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/app-router.js:50:11)
        at ErrorBoundaryHandler (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/error-boundary.js:59:9)
        at ErrorBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/error-boundary.js:72:11)
        at AppRouter (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/app-router.js:27:13)
        at ServerRoot (webpack-internal:///(app-client)/./node_modules/next/dist/client/app-index.js:147:11)
        at RSCComponent
        at Root (webpack-internal:///(app-client)/./node_modules/next/dist/client/app-index.js:164:11)
    c
    

    I hope this information helps in finding a more suitable solution for integrating @lit-labs/react with Next.js. Any suggestions or advice would be appreciated.

  8. jianliao commented on Apr 6, 2023

    @jianliao

    I believe that Attempt - 1 should ideally be the optimal solution, as the React component returned by createComponent(...) is already wrapped with React.forwardRef(...). Therefore, it shouldn't be necessary to wrap it again as in Attempt - 2.

  9. self-assigned this
    on Apr 13, 2023
  10. steveworkman commented on May 12, 2023

    @steveworkman
    Contributor

    +1

    Taking a wrapped react component I get this error trying to apply a ref

    import type { McButton } from '@org/mds-components-core';
    import { McButton as McButtonElement } from '@org/mds-react-wrapper';
    forwardRef<McButton>((props, ref) => {
      return <McButtonElement ref={ref} {...props} />;
    });

    error:

    Type 'ForwardedRef<McButton>' is not assignable to type 'Ref<McButton> | undefined'.
      Type '(instance: McButton | null) => void' is not assignable to type 'Ref<McButton> | undefined'.
        Type '(instance: import(".../mds-components-core/mc-button/index").McButton | null) => void' is not assignable to type '(instance: import(".../dist/mc-button/index").McButton | null) => void'.
          Types of parameters 'instance' and 'instance' are incompatible.
            Type 'import(".../dist/mc-button/index").McButton | null' is not assignable to type 'import(".../mds-components-core/mc-button/index").McButton | null'.
              Type 'import(".../dist/mc-button/index").McButton' is not assignable to type 'import(".../mds-components-core/mc-button/index").McButton'.
                Types have separate declarations of a private property 'button'.ts(2322)
    index.d.ts(140, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & Partial<ReactProps<McButton, { blur: EventName<CustomEvent<any>>; focus: EventName<CustomEvent<any>>; click: EventName<...>; }> & ElementWithoutPropsOrEventListeners<...> & EventListeners<...>> & RefAttributes<...>'
    
  11. augustjk commented on Sep 26, 2023

    @augustjk
    Member

    This is an upstream issue in Next.js: vercel/next.js#40769
    There's a PR linked to the issue that should fix this.

    There probably isn't much more we can do on our end. We shouldn't have any type errors with ref on our components if the ref is typed to be an instance of the original custom element class, but usage with next/dynamic has runtime problems. Workaround is to wrap with a component that takes the ref in a different prop name like forwardedRef.

    Thanks @AndrewJakubowicz for the excellent repro and investigation.

  12. moved this from 📋 Triaged to ✅ Done in Lit Project Boardon Sep 26, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions