Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use NPM package in React Component

I try to use Pannellum NPM package in my React component.

Pannellum's API can be used like this:

pannellum.viewer('panorama', {
    "type": "equirectangular",
    "panorama": "https://pannellum.org/images/alma.jpg"
});

I thought the following code:

import React, { Component } from 'react';
import './App.css';
import pannellum from 'pannellum';

class App extends Component {

  componentDidMount() {
    pannellum.viewer('panorama', {
      "type": "equirectangular",
      "panorama": "https://pannellum.org/images/alma.jpg"
    });
  }

  render() {
    return (
      <div id="panorama"></div>
    );    
  }
}

export default App;

would work. However it does not. I get TypeError: __WEBPACK_IMPORTED_MODULE_2_pannellum___default.a.viewer is not a function.

Tried also a different import statements: import { pannellum } from 'pannellum';, const pannellum = require('pannellum'); but these also don't work.

What's interesting, Pannellum's API javascript code is bundled and once I comment out componentDidMount() and try to use the API via Chrome Dev Tools console once the page is loaded, it works. However there are no CSS styles applied.

I clearly do something wrong. I have seen 360-react-pannellum package source code but I need access to the whole API, not just rendering so it does not suit my needs.

Thank you for your help.

like image 387
Dandry Avatar asked May 02 '18 12:05

Dandry


1 Answers

Looking at the source code of pannellum, it does not export any module but puts everything on the window object.

Try importing the code and using it directly from the window.

import React, { Component } from 'react';
import './App.css';
import 'pannellum';


class App extends Component {

  componentDidMount() {
    window.pannellum.viewer('panorama', {
      "type": "equirectangular",
      "panorama": "https://pannellum.org/images/alma.jpg"
    });
  }

  render() {
    return (
      <div id="panorama"></div>
    );    
  }
}

export default App;
like image 67
Alex Driaguine Avatar answered Oct 05 '22 21:10

Alex Driaguine