React Elements SDK
PublicSquare React Elements is a package designed to allow you to easily integrate PublicSquare JS SDK and Elements features in your React solution.
This section provides specific documentation for how to initialize a PublicSquare
instance using Hooks, pass it to your component tree with Context and then declare Elements Components in your code use the underlying Element.
Creating, mounting, updating and unmounting Elements is as simple as declaring them as a typical React Components and passing props.
Before You Begin
This SDK requires the use of a Publishable API Key. Go to your Developers section and click Reveal
for your Publishable Key
and copy the value.
Installation
- npm
- yarn
npm install --save @publicsquare/elements-react
yarn add @publicsquare/elements-react
@publicsquare/elements-js
separately when using our React package, unless you need to direct import a capability from it.Initialization
PublicSquareProvider
This Context Provider shares an instance of the React Elements SDK to your component tree, making it available for Elements Components or other custom components.
import {
PublicSquareProvider,
TextElement,
usePublicSquare,
} from "@publicsquare/publicsquare-react";
const App = () => {
return (
<PublicSquareProvider apiKey={apiKey}>
<MyComponent />
</PublicSquareProvider>
);
};
const MyComponent = () => {
// calling this hook with no attributes grabs the instance from Context
const { publicsquare } = usePublicSquare();
if (publicsquare) {
// able to call PublicSquare methods
}
return <CardElement id="myInput" />; // Element will also grab it from the Context
};
Using Refs
Refs are a way to access DOM nodes or React component instances.
refs
are utilized to store or receive (in the case of a callback ref) the underlying PublicSquare Elements instance, to tokenize their value or call one of its methods.
import { useRef } from "react";
import {
CardElement,
usePublicSquare,
} from "@publicsquare/publicsquare-react";
const MyForm = () => {
const { publicsquare } = usePublicSquare();
const cardRef = useRef(null);
const submit = async () => {
const card = cardRef.current;
try {
const tokens = await publicsquare.cards.create({
cardholder_name: 'John Smith',
card,
});
} catch (error) {
// check error details
}
};
return (
<PublicSquareProvider apiKey={apiKey}>
<CardEleemnt
id="card"
ref={cardRef}
/>
<div>
<button type="submit" onClick={submit} disabled={!publicsquare}>
Submit
</button>
</div>
</PublicSquareProvider>
);
};
When using Typescript, you can type-cast the element ref
to safely to a specific Elements Component type.
import { useRef } from "react";
import type { CardExpirationDateElement } from "@publicsquare/publicsquare-react/types";
const expirationDateRef = useRef(null);
expirationDateRef.current.month(); // Error TS2551: property doesn't exist
const expirationDateRef = useRef < CardExpirationDateElement > null;
expirationDateRef.current.month(); // no error