I am trying to use a variable from a library I have loaded in a script tag in my index.html
for my React components. I've loaded it as normal:
<head>
...
<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
<!-- gives me the 'Plaid' library -->
...
<title>React App</title>
</head>
However, when I try accessing Plaid
in my React components, it's undefined. I am confused because if I put in a debugger right before it, I can still access it. For instance, in my App.js
component, I have:
componentDidMount() {
debugger // can access 'Plaid' here
Plaid // throws error, 'Plaid' is undefined
}
Why is it that Plaid
throws an error, even though I can access it through the debugger?
Both React and the application code can stay as <script> tags with no changes.
Step:1 Open the HTML file you want to edit and add a div on which you want to add the React implementation. Provide a unique ID attribute to the div, as shown above. This will allow us to distinguish it from the element we want to implement. Here, we have added the scripts to load/import the React library.
Web Components provide strong encapsulation for reusable components, while React provides a declarative library that keeps the DOM in sync with your data. The two goals are complementary. As a developer, you are free to use React in your Web Components, or to use Web Components in React, or both.
I know this is late but I am answering this here for future users who had trouble doing what was described above.
The excepted answer is not the best way of going about integrating Plaid (or any external dependency in a <script>
tag). Ejecting a React app should be avoided when possible.
A better solution is to use the React built in way of accessing the global variable the script loads. You do this by accessing the window object (window.NameOfYourObject
). In this case it would be window.Plaid
.
In the context of the above example this would look like
this.linkHandler = window.Plaid.create({
clientName: 'plaid walkthrough demo',
product: ['transactions'],
key: 'YOUR KEY',
env: 'sandbox',
webhook: this.props.webhook,
token: this.props.token,
selectAccount: this.props.selectAccount,
longtail: this.props.longtail,
onLoad: this.handleLoad,
onSuccess: this.handleSuccess,
onExit: this.handleExit,
});
Having the script in the head works but it is also poor practice. It would be better to load the script with the component using something like react-load-script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With