htmlreactjscdnvis.js

Import External CDN in React Component


I created the react application using create-react-app npm. I wanted to add external CDN of vis.js in my react app.js component but I am not able to find a way to add it. I tried adding cdn in my html page and also used one extra html page for scripts and import in app.js component but it didn't work out.

App.js

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


class App extends Component {

  constructor(props) {
    super(props);
    console.log("In constructer");
  }

componentDidMount() {
  console.log("in componentDidMount");


  var nodes = new vis.DataSet([
    {id: 1, label: 'Node 1'},
    {id: 2, label: 'Node 2'},
    {id: 3, label: 'Node 3'},
    {id: 4, label: 'Node 4'},
    {id: 5, label: 'Node 5'}
  ]);

  // create an array with edges
  var edges = new vis.DataSet([
    {from: 1, to: 3},
    {from: 1, to: 2},
    {from: 2, to: 4},
    {from: 2, to: 5}
  ]);

  var data = {
    nodes: nodes,
    edges: edges
  };

  var options = {

    edges:{
      arrows: {
          to:     {enabled: true, scaleFactor:1, type:'arrow'},
          middle: {enabled: false, scaleFactor:1, type:'arrow'},
          from:   {enabled: false, scaleFactor:1, type:'arrow'}
      },
    },
    nodes:{
      shape:'square'
    },
    interaction:{
      dragNodes:false
    }
  };
  var network = new vis.Network(this.refs.myRef, data, options);
}

componentWillUnmount() {
  console.log("in componentWillUnmount");
}

render() {
  return (
    <div className="App">
      <Header/>
      <p className="App-intro">
        To get started, edit <code>src/App.js</code> and save to reload.
      </p>
      <div ref="myRef"></div>;
    </div>
  );
}
}

class Header extends Component {

  render() {
    return (
      <div className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <h2>Welcome to React</h2>
      </div>
    );
  }
}


export default App;

Now I wanted to add this script in my app.js so that I can use new vis.* methods.

<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.20.0/vis.min.js"></script>

How can I add this cdn in my component?


Solution

  • Add the CDN normally in Your index.html file and then in Your React component use window.* where the star is the name of the function to access this function. For example if this CDN has a function countSomething() You invoke it by using window.countSomething().