0

So I'm trying to build a generic component in a separate repo from a project. The components repo is an npm package. I will include the code so you can tell me what I'm doing wrong?

My component is in: src/components/table/Table.tsx;

really simple code:

const Table = () => {
  const [test, setTest] = useState(1);
  return <div>Test</div>
}

export default Table;

Then I have the index.ts file with this:

import Table from './components/table/Table.tsx';
export { Table };

Then I have the package.json with the build command for development:

"main": "dist/bundle.js",
"scripts": {
  "dev": "webpack --watch --mode development"
} 

Then the webpack config file:

const path = require("path");

module.exports = {
  entry: "./src/index.ts",
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: "babel-loader",
        exclude: /node_modules/
      },
    ]
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
    alias: {
      "@": path.resolve(__dirname, "src")
    }
  },
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
    libraryTarget: "umd",
    library: "my-library"
  }
};

And then in the other project I have the package JSON where I import my package (locally for now, for developemnt):

"dependencies": {
    "@myuser/my-library": "file:../my-library",
}

And then I import the component:

import { Table } from '@myuser/my-library';

And then use it:

const MyComponent = () => {
  return (
    <div>
      <Table />
    </div>
  )
}

And it throws:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

But if I remove the useState in the Table component then it works all perfectly.

zhulien
  • 5,145
  • 3
  • 22
  • 36
nick
  • 2,819
  • 5
  • 33
  • 69
  • 1
    Possible duplicate - https://stackoverflow.com/questions/64283813/invalid-hook-call-on-npm-link-library. At least this was the issue for me when I encountered a similar issue – Brian Thompson Oct 18 '21 at 19:19
  • I already have react in peerDependencies, but it's also in devDependencies. Should I delete it from the later and npm i? – nick Oct 18 '21 at 19:25
  • 1
    What version of react are you using? Check it's the same as react-dom. Should be >= 16.8 (`npm list react react-dom`). – tavoyne Oct 18 '21 at 19:34
  • I'm using 16.13.1 for both, same as the other project... – nick Oct 18 '21 at 19:59

0 Answers0