1

I'm using the default starting project from create-react-app, with the following folder structure:

app
--public
----index.html
--src
----App.js
----components
-------map.js

I have included an external CDN library in the index.html body tag. However, I'm confused about how to use the methods of this library in my map.js component.

Just writing the library methods in my map.js, returns:

Failed to compile
./src/components/map.js
  Line 5:  'L' is not defined  no-undef 

Is there any way I can include a JS CDN library in my React components without actually importing the library as React Component via npm install?

4
  • How did you include the library? Did it include it before the bundle file? Commented Feb 16, 2018 at 21:16
  • I still haven't run npm build on my app. I'm in the dev process, if that is what you are asking? Does this means that I will have to bundle every time I save in order for the CDN library to be available? Commented Feb 16, 2018 at 21:18
  • @BlueBird03 Is there no npm package of that library? Commented Feb 16, 2018 at 21:19
  • Please show the <script> definitions from your index.html. Commented Feb 16, 2018 at 21:26

2 Answers 2

3

You're loading a component in the DOM, React has no knowledge of the DOM. So you need to create a wrapper component for the DOM library and use the ref prop to access it. If you're a beginner please use React libraries exclusively, if you need third party libraries, start by reading the React docs https://reactjs.org/docs/integrating-with-other-libraries.html about third party libraries.

Btw, the error you're seeing is most likely a babel error which can't transform your ES6 classes, it can't find the library you require. I think there are options to configure global environment, so it ignores these errors (but that probably means ejecting from cra).

Sign up to request clarification or add additional context in comments.

Comments

3

Take a look at this link:

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#using-the-public-folder

To reference assets in the public folder, you need to use a special variable called PUBLIC_URL.

Inside index.html, you can use it like this:

Only files inside the public folder will be accessible by %PUBLIC_URL% prefix. If you need to use a file from src or node_modules, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build.

When you run npm run build, Create React App will substitute %PUBLIC_URL% with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL.

In JavaScript code, you can use process.env.PUBLIC_URL for similar purposes:

It will show you how to do it the way create-react-app prefers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.