MatejR
MatejR

Reputation: 86

Component from a third party library not working on server side in NextJS

I am stumbling upon an issue that is a bit confusing for me.

I recently started working with new NextJS v13 that uses React server components.

I am using it in a project that relies on a small private third party library I wrote that is shared/used between multiple other project.

And inside of it I have the following component:

/* eslint-disable react/jsx-no-useless-fragment */
import React, { Fragment } from 'react';
import type { ReactNode } from 'react';

import type { Item, ForProps } from './For.types';

const renderItem = <T extends Item>(
  item: T,
  children: (item: T) => ReactNode,
  index: number,
  itemFallback?: ReactNode
) => {
  const key = Object.prototype.hasOwnProperty.call(item, 'id')
    ? item.id
    : index;

  return (
    <Fragment key={key}>{children(item) || itemFallback || null}</Fragment>
  );
};

function For<T extends Item>(props: ForProps<T>) {
  const { each, children, fallback, itemFallback } = props;

  return (
    <>
      {each && each.length > 0
        ? each.map((item, index) =>
            renderItem(item, children, index, itemFallback)
          )
        : fallback || null}
    </>
  );
}

export default For;

It is just a basic For components that is a wrapper for the array map method that just handles missing keys and has a fallback.

For whatever reason, when bundled and used in my NextJS project:

import { For } from '@bidgrupa/ui';

export function ExampleComponent() {
  const arr = [1, 2, 3, 4, 5];

  return <For each={arr}>{num => <h1>{num}</h1>}</For>;
}

I get the following error:

TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component

So I decided to see if the component itself will work if I copy and paste it inside the NextJS project directly and it worked!

So is there something I am missing? Maybe missed in new documentation?

Any insights/help would be appreciated!

Upvotes: 0

Views: 554

Answers (1)

MatejR
MatejR

Reputation: 86

I managed to figure out the issue.

My case was very specific but hope it helps; for whoever is using TSDX to bundle their third party libraries, because there is only one entry point for exporting files, for whatever reason react-helmet-async (although not used anywhere in my new project) was causing the issue.

Upvotes: 0

Related Questions