mrks
mrks

Reputation: 5631

Importing functional react component from npm modules returns invalid hook call

I have a repository created to share react components between different clients.

A shared component looks like this:

import React from "react";
import { useTranslation } from "react-i18next";
import IconProjects from "../Icons/Icon_Projects";

interface Props {
  links: {
    [key: string]: Link;
  };
}

interface Link {
  name: string;
  url: string;
  icon: string;
}

export function Header(props: Props) {
  const { t } = useTranslation();
  const { links } = props;
  const showIcon = (icon: string) => {
    switch (icon) {
      case "products":
        return <IconCoffeePackage className="header__icon" />;
      default:
        break;
    }
  };
  return (
    <header className="header">
      <h1>Header</h1>
      <ul>
        {links
          ? Object.entries(links).map(([key, link]) => (
              <li key={key}>
                <a href={link.url}>
                  {showIcon(link.icon)} {t(link.name)}
                </a>
              </li>
            ))
          : ""}
      </ul>
    </header>
  );
}

This is my folder structure for the shared repo:

- dist
-- components
--- Header
---- Header.js
-- index.d.ts
-- index.js
-- node_modules
- src
-- components
--- Header
---- Header.tsx
-- index.ts
node_modules
tsconfig.json

My index.ts is like this:

export { Header } from "./components/Header/Header";

With tsconfig I create a dist folder:

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": false,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "typeRoots": [
      "./node_modules/@types/",
      "./types"
    ]
  },
  "include": [
    "src"
  ]
}

When I import now the Header component from my shared repo like this

import { Header } from 'shared-components';

I get the following error in my client:

react.development.js:1431 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

But this does not happen when I copy the Header component into the client directly.

Can somebody give me a tip?

Upvotes: 0

Views: 116

Answers (1)

yeernet
yeernet

Reputation: 26

Because your component is running in a different react instance. So this does not happen when you copy the Header component into the client directly.

Remove dependencies(react and react-dom) in your component, and rebuild it.

Upvotes: 1

Related Questions