Skip to content

Instantly share code, notes, and snippets.

@proko
Created November 3, 2019 16:37
Show Gist options
  • Select an option

  • Save proko/c121374c66e19c271b18cca744de0cdf to your computer and use it in GitHub Desktop.

Select an option

Save proko/c121374c66e19c271b18cca744de0cdf to your computer and use it in GitHub Desktop.
React hook for Braintree Hosted Fields
import { useState, useEffect } from 'react';
import client from 'braintree-web/client';
import hostedFields from 'braintree-web/hosted-fields';
const fieldsInnerStyles = {
input: {
'font-size': '14px',
},
'input.invalid': {
color: 'red',
},
'input.valid': {
color: 'green',
},
};
export function useHostedFields() {
const [fields, setFields] = useState();
const [isSubmitDisabled, setIsSubmitDisabled] = useState(true);
useEffect(() => {
async function setup() {
try {
const clientInstance = await client.create({
authorization: process.env.TOKENIZATION_SANDBOX,
});
const hostedFieldsInstance = await hostedFields.create({
client: clientInstance,
styles: fieldsInnerStyles,
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111',
},
cvv: {
selector: '#cvv',
placeholder: '123',
},
expirationDate: {
selector: '#expiration-date',
placeholder: '10/2019',
},
},
});
setFields(hostedFieldsInstance);
setIsSubmitDisabled(false);
} catch (error) {
return `error preparing hosted fields: ${error}`;
}
}
setup();
}, []);
return [fields, isSubmitDisabled];
}
@jfaraz
Copy link
Copy Markdown

jfaraz commented Aug 17, 2021

Do you have complete example to use this hook?

@proko
Copy link
Copy Markdown
Author

proko commented Aug 17, 2021

Do you have complete example to use this hook?

Sorry, not anymore! I am using Stripe nowadays. Not even sure if Braintree api is still the same to be honest.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment