Open anpriyadar opened 1 year ago
I had the same problem and for me it came down to two issues requiring two fixes:
react
and react-dom
as devDependencies
. While they should be peerDependencies
so that they are shared with your other react project. If not, the component library and your other react project may use different versions of react
and react-dom
. See https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-reactChange your package.json
like so:
{
...
"devDependencies": {
...
// REMOVE THESE:
"react": "<your version>",
"react-dom": "<your version>",
...
},
"peerDependencies": {
// ADD THESE:
"react": "<your version>",
"react-dom": "<your version>"
},
...
}
Now make sure this prints false:
// Add this in node_modules/react-dom/index.js
window.React1 = require('react');
// Add this in your component file
require('react-dom');
window.React2 = require('react');
console.log(window.React1 === window.React2);
react
and react-dom
as external. See https://github.com/facebook/react/issues/13991#issuecomment-1190000201Change your rollup.config.ts
like so:
import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";
import dts from "rollup-plugin-dts";
import postcss from "rollup-plugin-postcss";
const packageJson = require("./package.json");
export default [
{
input: "src/index.ts",
output: [
{
file: packageJson.main,
format: "cjs",
sourcemap: true,
},
{
file: packageJson.module,
format: "esm",
sourcemap: true,
},
],
plugins: [
resolve(),
commonjs(),
typescript({ tsconfig: "./tsconfig.json" }),
postcss(),
],
// ADD THIS:
external: ["react", "react-dom"]
},
{
input: "dist/esm/types/index.d.ts",
output: [{ file: "dist/index.d.ts", format: "esm" }],
plugins: [dts()],
external: [/\.(css|less|scss)$/],
},
];
I hope this works for you!
@alexeagleson it would be nice if these changes are pulled into this repo so others don't run into the same problem :). I can make a PR if you wish
This fix works with me.
This problem can also come up when you use npm link or an equivalent. In that case, your bundler might “see” two Reacts — one in application folder and one in your library folder. Assuming myapp and mylib are sibling folders, one possible fix is to run npm link ../myapp/node_modules/react from mylib. This should make the library use the application’s React copy.
from React documentation.
it works so sweet. thanks
Could anyone please give git repo to integrate mui library to our custom library and develop over it.
When i add Material UI component and try to use component in another react project, it throw Error Regarding hooks.
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:
can you please help me to understand why i am getting this ?