HarveyD / react-component-library

A project skeleton to get your very own React Component Library up and running using Rollup, Typescript, SASS + Storybook
https://blog.harveydelaney.com/creating-your-own-react-component-library/
MIT License
790 stars 167 forks source link

Invalid hook call #33

Closed nimahkh closed 3 years ago

nimahkh commented 3 years ago

Hello guys, and thanks to @HarveyD for this great repository . I have a problem when I use the code below:

import React from "react";

import { TestComponentProps } from "./TestComponent.types";

import "./TestComponent.scss";

const TestComponent: React.FC<TestComponentProps> = ({ theme }) => {
  const [state, setState] = React.useState(null)
  return (
  <div
    onClick={()=>setState("HI")}
    data-testid="test-component"
    className={`test-component test-component-${theme}`}
  >
    <h1 className="heading">I'm the test component</h1>
    <h2>Made with love by Harvey {state}</h2>
  </div>
)};

export default TestComponent;

it gives me this error on test project :

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:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

And it is how I used it on my Test:

import logo from './logo.svg';
import './App.css';
import {TestComponent} from "react-component-library"

function App() {
  return (
    <div className="App">
      <TestComponent/>
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

What is wrong with it?

nimahkh commented 3 years ago

I just read your comment in the article that you wrote. https://blog.harveydelaney.com/creating-your-own-react-component-library/

When the component library is symlinked, the devDependencies are persisted (react + react-dom). This will cause the duplicate React issue linked above.

I recommend doing this:

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.

So I published it on npm and install it from npm, it fixed now, great