Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  170] [ 4]  / answers: 1 / hits: 26261  / 6 Years ago, thu, march 22, 2018, 12:00:00

I'm trying to use a third-party library in my React app (built via create-react-app) that is normally loaded via a <script> tag in html file.:




index.html




    ...
<script src=some-library.js></script>
</body>
</html>


The script basically just calls itself at the end of the file:




some-library.js




function foo() {
...
}

foo();


There are no modules or export statements, so it's not immediately clear to me how to use this in my React app.



After installing the library with npm, I have tried using import and require() statements in my App.js file, without success:




App.js




import some-library;                          // doesn't work
require(some-library); // doesn't work
const SomeLibrary = require(some-library); // doesn't work

...


Some instructions about using third-party libraries in React suggest using the library within one of the React lifecycle hooks, like componentDidMount(), but there's no function I'm able to call from the library:




App.js




import React, { Component } from react;
import * as SomeLibrary from some-library;

class App extends Component {
componentDidMount() {
SomeLibrary.foo(); // doesn't work (wasn't exported in some-library)
}

render() {
...
}
}

export default App;


The only solution I've been able to find is to copy some-library.js into my public/ folder, and then include it as a <script> tag in index.html. This seems like an awkward solution though.



Is there a way to import this library in my src/ JavaScript files for React instead of just as a <script> tag in index.html?



(For reference, the specific library I'm trying to use is https://github.com/WICG/focus-visible/.)


More From » reactjs

 Answers
10

I was able to get this working by directly importing the file from the library's dist folder, instead of just naming the library by itself.



I also needed to make sure to import the library first before any other libraries (e.g. React).




App.js




import some-library/dist/some-library.js;
import React, { Component } from react;
...

[#54877] Monday, March 19, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anikas

Total Points: 258
Total Questions: 102
Total Answers: 95

Location: Monaco
Member since Sun, Jan 16, 2022
2 Years ago
;