Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External react component cannot see React.Component

The external React component says Uncaught TypeError: Cannot read property 'Component' of undefined when I link as npm package.

I link a package in package.json as "react-mapbox": "https://github.com/varya/react-mapbox.git". Then I use it in code

import {render} from 'react-dom';

import MapBox from "react-mapbox";

render(
  <div>
    <h1>Hello, world!</h1>
    <MapBox />
  </div>
  ,
  document.getElementById('example')
);

But nothing works, I get that error. The full repo is here https://github.com/varya/react-mapbox-test I made a small example to illustrate.

The react-mapbox package is my own, maybe I build it wrongly? This is its repo https://github.com/varya/react-mapbox I built it with webpack, like that https://github.com/varya/react-mapbox/blob/master/webpack.config.js As I suppose, this build does not include react package assuming that this will be at the project which link it. But the component still do not see react object.

UPD

I added import React from 'react'; as @aulizko suggested, but this only provided React object onto a page. It still was not visible for the component.

To fix this I had to provide this changes https://github.com/varya/react-mapbox/commit/2687d66025aaa84553a79850aa8686e88f1f39d9 I required react in the code of the component as well. And I have to build with Babel. For some reason the webpack build gives the same error even if react is required. I created a branch to illustrate this https://github.com/varya/react-mapbox/tree/webpack Now I'm happy with Babel, but with this branch you can see what's wrong with webpack if interested.

like image 862
Varvara Stepanova Avatar asked Oct 15 '15 11:10

Varvara Stepanova


1 Answers

You're probably bundling your module as UMD which is causing the bundle to utilized a global React variable which doesn't exist in the consumer app. You need to export the bundle as a CommonJS or AMD module using https://webpack.github.io/docs/configuration.html#output-librarytarget. Simple add libraryTarget: 'commonjs2 or libraryTarget: 'amd' to the output key in the webpack config and make sure you are importing react in your component.

like image 56
slightlytyler Avatar answered Oct 31 '22 20:10

slightlytyler