teambit / envs

Component development environments for the Bit community
https://bit.dev/bit/envs
Other
63 stars 9 forks source link

duplicate react installed which causes invalid hook error #127

Closed jink-e closed 4 years ago

jink-e commented 4 years ago

Describe the bug

react component

Steps to Reproduce

  1. write a component use styled-components
    
    // src/components/TestButton
    import React from 'react';
    import styled from 'styled-components';

const Wrapper = styled.div color: red; text-align: center; vertical-align: middle; line-height: 50px; width: 100px; border: 1px solid blue; border-radius: 10px; ;

const TestButton = props => (

{props.children}

);

export default TestButton;

2. bit add src/components/TestButton && bit build
3. bit tag --all
4. bit export local-scope
5. create a new app `create-react-app new-app && cd new-app` 
6. bit import local-scope/test-button
7. use imported bit component
```js
// src/App.js
import React from 'react';
import TestButton from '@bit/boz-scope.test';
import './App.css';

function App() {
  return (
    <>
      <TestButton>Hello</TestButton>
    </>
  );
}

export default App;
  1. yarn && yarn start
  2. invalid hook error occurs
    
    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:
  3. You might have mismatching versions of React and the renderer (such as React DOM)
  4. You might be breaking the Rules of Hooks
  5. 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.
  6. remove ./components/test-button/node_modules/react
  7. yarn && yarn start
  8. error disappear

    Expected Behavior

no invalid hook error appear no need of manually removing react in components/test-button/node_modules

Screenshots, exceptions and logs

If applicable, add screenshots, exceptions, and logs to help explain your problem.

Specifications

Additional context

Add any other context about the problem here.

itaymendel commented 4 years ago

Hi,

I assume that if you run bit show on the component you'll see that both React and Styled-components are set as dependencies. When setting components for reusability you should set some dependencies to be peerDependencies instead. In React, these should be react and react-dom. Additionally, styled-components needs to be a singleton in the project, so in your case, you'd want to set it as a peer as well.

You can read more about it in Bit's guidelines for React. You can also use overrides to configure it for components.

jink-e commented 4 years ago

Thank you so much! @itaymendel This can be solved by adding peerDependencies

// components/test-button/package.json
"peerDependencies": {
    "react": "^16.13.1",
    "react-dom": "^16.13.1"
  },

Appreciate agin :)