To import a JavaScript package from a CDN or a <script>
tag in a React application, you typically use the window
object to access the globally available functions or variables defined by the package.
To do this, we can:
1. Using a CDN directly in your HTML file
In your public/index.html
file, include the script tag for the package you want to use:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>React App</title>
</head>
<body>
<div id="root"></div>
<!-- Include the script tag for the package from CDN -->
<script src="https://cdn.example.com/package.js"></script>
</body>
</html>
Then, in your React component, you can access the functions or variables defined by the package using the window
object:
import React from "react";
function MyComponent() {
React.useEffect(() => {
// Access functions/variables from the package using window
window.packageFunction();
}, []);
return <div>{/* Your component JSX */}</div>;
}
export default MyComponent;
2. Using npm/yarn package with a CDN fallback
If the package is available on npm/yarn, you can install it as a dependency:
npm install package-name
Then, in your component, you can use the package like any other npm/yarn package:
import React, { useEffect } from "react";
import packageFunction from "package-name";
function MyComponent() {
useEffect(() => {
packageFunction();
}, []);
return <div>{/* Your component JSX */}</div>;
}
export default MyComponent;
If the package is not available on npm/yarn and you still want to use a CDN, you can follow the same approach as mentioned in the first method, by including the script tag in your HTML file and accessing the functions or variables using the window
object.
Make sure to replace 'package-name'
with the actual package name, and 'https://cdn.example.com/package.js'
with the actual CDN URL.