Search code examples
reactjsnpmreact-routercreate-react-app

Issues importing a custom module component that uses React-Router-Dom


While trying to import a component from another project of mine via turning the imported project into a node module, the component comes out as undefined. This component uses React-Router-Dom which has its own defined:

<Link to=""> <Link />

This component is then imported into a parent project with its own router, however on compile, the component is found undefined.

What could be the problem causing this?

Attempts:

  1. Removed all react-router-dom imports from the component and exported the component as a pure html file results in a successful exported component.

  2. Removed the router from the exported component and left only the Link wrapper.

  3. Removed the need for history prop

The exported component:

     export default function ExampleWrapper({ history }) {
       return (
        <div>
           <Router>
            <div>
                <Link to="/example">
                    <button>Example</button>
                </Link>

                <Link to="/secondExample">
                    <button>secondExample</button>
                </Link>
            </div>

            <Fragment >
                <Switch >
                    <Route path="/example" exact component={Example} />
                    <Route path="/secondExample" exact component={SecondExample} />
                </Switch>
            </Fragment>
          </Router>
        </div>

The index for exposing the import within the module index:

export default Example;

export { SecondExample, ThirdExample, ExampleWrapper};

The component using the node module exports:

import { ExampleWrapper } from 'create-react-library';

function App() {
    return (
        <div className="App">

            <ExampleWrapper history={history} />

            <Router history={history}>
                <Navbar />
                <header className="App-header">
                    <div className="columns is-marginless">
                       <Fragment>
                           <Switch>
                              <Route path="/admin/home" exact component={Home} />
                           </Switch>
                        </Fragment>
                     </div>
                 </header>
             </Router>
         </div>
   );
}

Error Code:

Cannot read property 'dispose' of undefined
./node_modules/react-dev-utils/webpackHotDevClient.js
C:/Users/userName/DEV/concepts/admin-ui/node_modules/react-dev-utils/webpackHotDevClient.js:45

Solution

  • You need to edit the webpack.config.js in your parent project adding the dependencies your child project will need.

    In your case:

      externals: (isEnvDemo || isEnvProduction)
      ? {
        react: 'react',
        'react-dom': 'react-dom',
        'react-router-dom': 'react-router-dom'
      }