0

I have several projects that share many components, so I decided to create a library. Now, some components are connected to Redux or to React Route. I supposed that as the componentes are used inside the app, being wrapped by Redux and Router providers, It would have access to the corresponding context, however that is not the case.

import { Provider } from 'react-redux'
import store from 'store'
import { MyLibComponent } from 'myLibComponent'

<Provider store={store}>
  <BrowserRouter>
    <MyLibComponent />
  </BrowserRouter>
</Provider>
import { useSelector } from 'react-redux'; 
import { useLocation } from 'react-router-dom';

const MyLibComponent = () => {
  const reducer = useSelector(state => state.reducer)
  const location = useLocation()

  ...
}

I receive an error indicating that MyLibComponent has no access to "store, and useLocation returns undefined. I was able to use Redux in these components by passing "store" as a prop, and for componentes using React Router I had to pass the methods I wanted to use as props.

However, I would like to know if it is possible to connect the lib components to these context or why it is not possible to do so.

Making some research, I found these threads:

How to share context between different component libraries in react?

How do I share context between a library component, and my application component? - Attending to this, It seems that with material-ui is possible to connect to Theme by installing material as devDependencie in the library. In my case I installed redux and react-router but it didn't work.

Javier
  • 428
  • 5
  • 12

1 Answers1

0

I found the solution. Components library were not connected to the app context because a wrong configuration of webpack. All I had to do is to add react-redux and react-router-dom to the webpack.config.js external section:

// webpack.config.js

...
externals: {
    react: {
      commonjs: 'react',
      commonjs2: 'react',
      amd: 'React',
      root: 'React',
    },
    'react-dom': {
      commonjs: 'react-dom',
      commonjs2: 'react-dom',
      amd: 'ReactDOM',
      root: 'ReactDOM',
    },
    'react-redux': {
      commonjs: 'react-redux',
      commonjs2: 'react-redux',
      amd: 'ReactRedux',
      root: 'ReactRedux',
    },
    'react-router-dom': {
      commonjs: 'react-router-dom',
      commonjs2: 'react-router-dom',
      amd: 'ReactRouterDOM',
      root: 'ReactRouterDOM',
    },
  },
...

Now all componentes has access to the app Redux, as well as to Router context.

Javier
  • 428
  • 5
  • 12