I have to use an external library for payments called Yoco, and to use it they say I should put the script link in the <head>
, then create a form with an id of "card-frame" and then run the following script:
<script>
var sdk = new window.YocoSDK({
publicKey: 'pk_test_example12345678'
});
// Create a new dropin form instance
var inline = sdk.inline({
layout: 'field',
amountInCents: 2499,
currency: 'ZAR'
});
// this ID matches the id of the element we created earlier.
inline.mount('#card-frame');
</script>
It is best practice in React to mount something to a component with the .mount() method, or is there a different way that I should do it?
I’m not even exactly sure what the "mount()" is supposed to do because if I log the "inline" element I just get this object:
{
layout: 'field',
amountInCents: 2499,
currency: 'ZAR'
}
So I have no clue where the form elements (like the buttons and fields) come from since they are not in the "inline" element. But if I put this in vanilla HTML it does generate a form.
2
Answers
Best practice in React to load external libraries is to use
useEffect
. You can include the link to the library in thehead
of your app and then use theuseEffect
hook to initialize it.The
"mount()"
method is used to attach the form created by theYocoSDK
to a specific element on the page. In this case, the form is attached to the element with the id"card-frame"
.In
React
, you can still use the"mount()"
method to attach the form to a specific component by using aref
. You can create aref
for the component where you want to attach the form and then pass that ref to the"mount()"
method.Here’s an example:
In this example, we create a ref using the useRef hook and attach it to the div with id "card-frame". We then pass this ref to the "mount()" method. When the component mounts, the YocoSDK form will be attached to the div referenced by the ref.
Note that we also add a cleanup function that calls
"unmount()"
when the component unmounts. This is to ensure that any event listeners or resources used by the SDK are cleaned up properly.Regarding the form elements,
YocoSDK
handles the rendering of the form fields and buttons internally. The "inline" method returns an instance of the"Dropin"
class, which has methods for interacting with the form and submitting the payment details. The object you see when logging the"inline"
variable is just a representation of the options you passed in when creating the form.