Kristi Jorgji
Kristi Jorgji

Reputation: 1739

How to fix "Invalid hook call" during a simple React MUI Component Library creation?

I am trying to build a public repository in which I will export a couple of React components build in typescript.

I added storybook and ts config fine. I can develop in storybook but the problem I face happens when I import the compiled/build package and use this component. I get the following error:

enter image description here

I don't use any react hook directly in the component. I just use the mui/lab TextField for testing.

Steps to reproduce:

  1. Clone my repository at https://github.com/kristijorgji/react-mui-components
  2. run yarn build to compile into the relative lib folder
  3. Use the generated library into one empty react project. You can add the local library like this
yarn add react-mui-components@file:/yourpath/react-mui-components

Then have a component like I did in your client project

import React, { useState } from 'react';

import { Button, Scheduler } from 'react-mui-components';

const ClientTest: React.FC = () => {
    return (
        <>
            <Button label={'kristi'} primary={false} />
            <Scheduler />
        </>
    );
};
export default ClientTest;

The above will end up in error that I showed. I also use react mui wrapper in the client project App.tsx and inside it render the above ClientTest

If I render only <Button label={'kristi'} primary={false} /> it works fine. The problem is with Scheduler component that is using react-mui TextField

I also specified in peerDependencies to use same react version as in my client project for

  "peerDependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@mui/icons-material": "^5.11.0",
    "@mui/lab": "^5.0.0-alpha.113",
    "@mui/material": "^5.11.1",
    "react": "17.0.1",
    "react-dom": "17.0.1"
  }

I am using same versions in the client dependencies section

Upvotes: 2

Views: 528

Answers (1)

Kristi Jorgji
Kristi Jorgji

Reputation: 1739

I fixed this myself. The problem was that react was included 2 times in the build via webpack (somehow). One time included via node_modules folder of the client project and one time via node_modules of the library.

To fix that, I had to npm link react and react-dom of the library to the one of the client

clientProjectPathNodeModules=somepath/node_modules
npm link "$clientProjectPathNodeModules"/react
npm link "$clientProjectPathNodeModules"/react-dom

Afterward all worked smooth without the error.

PS: I Added the fix script in my public repository as well + the instructions on the README.md

Upvotes: 0

Related Questions