emmawedekind
emmawedekind

Reputation: 51

create-react-library not working with styled components

I'm using create-react-library to build my component library, and I've attempted to use Styled Components, but I keep getting a React hooks error.

Here's my code: https://github.com/emmabostian/component-library

And here's the error:

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

I am not using React hooks anywhere, my React and React DOM versions match and I do not have multiple versions of React.

Upvotes: 5

Views: 1469

Answers (3)

Sooraj Nair H S
Sooraj Nair H S

Reputation: 37

I've recently used create-react-library, and had encountered the same issue. The error message exactly makes sense in this case. The issue will not happen when you actually publish the package and consume it at a consumer application. This means, the problem is with your example folder. If you look at package.json, that's inside example folder, you can see there are library references for react, react-scripts, react-dom etc. Referring those with file protocol like below will solve your problem.

  "dependencies": {
    "library-name": "file:..",
    "react": "file:../node_modules/react",
    "react-dom": "file:../node_modules/react-dom",
    "react-scripts": "file:../node_modules/react-scripts"
    "node-sass": "file:../node_modules/node-sass"
  },

Clear your node_modules as well as package-lock.json before trying this.

Upvotes: 0

coderbyheart
coderbyheart

Reputation: 113

The dependencies in the included example project are very outdated.

Instead I set up a new separate example project, which perfectly renders your button:

npx create-react-app component-library-example
cd component-library-example
npm install --save emmas-super-cool-component-library
npm start

App.js:

import React from "react";
import { PrimaryButton } from "emmas-super-cool-component-library";

const App = () => (
  <PrimaryButton
    onClickHandler={() => {
      alert("clicked");
    }}
  >
    text
  </PrimaryButton>
);

export default App;

Result:

App

Upvotes: 1

dorriz
dorriz

Reputation: 2679

Check your package.json file you appear to have dependencies react / react-dom version 16 but peer dependencies for versions 15 . I think this is the cause of your problem , remove the peer dependencies. Also you don't need to write your components as class based if all you are doing is rendering use a functional component approach instead.

Upvotes: 1

Related Questions