Git Product home page Git Product logo

react-stripe-elements's Introduction

Stripe Elements for React

React components that help you quickly add Stripe Elements to your React app.

build status npm version

This project is a thin React wrapper around Stripe.js and Stripe Elements. It allows you to add Elements to any React app, and manages the state and lifecycle of Elements for you.

The Stripe.js / Stripe Elements API reference goes into more detail on the various customization options for Elements (e.g. styles, fonts).

This project is currently in beta. The API presented below may undergo significant changes until we hit a stable release.

Getting started

Installation

First, install react-stripe-elements.

Using yarn:

yarn add react-stripe-elements

Using npm:

npm install --save react-stripe-elements

Using UMD build (exports a global ReactStripeElements object):

<script src="https://unpkg.com/react-stripe-elements@latest/dist/react-stripe-elements.min.js"></script>

Then, load Stripe.js in your application:

<script src="https://js.stripe.com/v3/"></script>

You're good to go!

The Stripe context (StripeProvider)

In order for your application to have access to the Stripe object, let's add StripeProvider to our root React App component:

// index.js
import React from 'react';
import { render } from 'react-dom';
import {StripeProvider} from 'react-stripe-elements';

import MyStoreCheckout from './MyStoreCheckout';

const App = () => {
  return (
    <StripeProvider apiKey="pk_test_12345">
      <MyStoreCheckout />
    </StripeProvider>
  );
};

render(<App />, document.getElementById('root'));

Element groups (Elements)

Next, when you're building components for your checkout form, you'll want to wrap the Elements component around your form. This groups the set of Stripe Elements you're using together, so that we're able to pull data from groups of Elements when you're tokenizing.

// MyStoreCheckout.js
import React from 'react';
import {Elements} from 'react-stripe-elements';

import CheckoutForm from './CheckoutForm';

class MyStoreCheckout extends React.Component {
  render() {
    return (
      <Elements>
        <CheckoutForm />
      </Elements>
    );
  }
}

export default MyStoreCheckout;

Setting up your payment form (injectStripe)

Use the injectStripe Higher-Order Component (HOC) to build your payment form components in the Elements tree. The Higher-Order Component pattern in React can be unfamiliar to those who've never seen it before, so consider reading up before continuing. The injectStripe HOC provides the this.props.stripe property that manages your Elements groups. You can call this.props.stripe.createToken within a component that has been injected to submit payment data to Stripe.

⚠️ NOTE injectStripe cannot be used on the same element that renders the Elements component; it must be used on the child component of Elements. injectStripe returns a wrapped component that needs to sit under <Elements> but above any code where you'd like to access this.props.stripe.

// CheckoutForm.js
import React from 'react';
import {injectStripe} from 'react-stripe-elements';

import AddressSection from './AddressSection';
import CardSection from './CardSection';

class CheckoutForm extends React.Component {
  handleSubmit = (ev) => {
    // We don't want to let default form submission happen here, which would refresh the page.
    ev.preventDefault();

    // Within the context of `Elements`, this call to createToken knows which Element to
    // tokenize, since there's only one in this group.
    this.props.stripe.createToken({name: 'Jenny Rosen'}).then(({token}) => {
      console.log('Received Stripe token:', token);
    });

    // However, this line of code will do the same thing:
    // this.props.stripe.createToken({type: 'card', name: 'Jenny Rosen'});
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <AddressSection />
        <CardSection />
        <button>Confirm order</button>
      </form>
    );
  }
}

export default injectStripe(CheckoutForm);

Using individual *Element components

Now, you can use individual *Element components, such as CardElement, to build your form.

// CardSection.js
import React from 'react';
import {CardElement} from 'react-stripe-elements';

class CardSection extends React.Component {
  render() {
    return (
      <label>
        Card details
        <CardElement style={{base: {fontSize: '18px'}}} />
      </label>
    );
  }
};

export default CardSection;

Component reference

<StripeProvider>

All applications using react-stripe-elements must use the <StripeProvider> component, which sets up the Stripe context for a component tree. react-stripe-elements uses the provider pattern (which is also adopted by tools like react-redux and react-intl) to scope a Stripe context to a tree of components. This allows configuration like your API key to be provided at the root of a component tree. This context is then made available to the <Elements> component and individual <*Element> components that we provide.

An integration usually wraps the <StripeProvider> around the application’s root component. This way, your entire application has the configured Stripe context.

Props shape

This component accepts all options that can be passed into Stripe(apiKey, options) as props.

type StripeProviderProps = {
  apiKey: string,
};

<Elements>

The Elements component wraps groups of Elements that belong together. In most cases, you want to wrap this around your checkout form.

Props shape

This component accepts all options that can be passed into stripe.elements(options) as props.

type ElementsProps = {
  locale?: string,
  fonts?: Array<Object>,
  // The full specification for `elements()` options is here: https://stripe.com/docs/elements/reference#elements-options
};

<*Element> components

These components display the UI for Elements, and must be used within StripeProvider and Elements.

Available components

(More to come!)

  • CardElement
  • CardNumberElement
  • CardExpiryElement
  • CardCVCElement
  • PostalCodeElement

Props shape

These components accept all options that can be passed into elements.create(type, options) as props.

type ElementProps = {
  className?: string,
  elementRef?: (StripeElement) => void,

  // For full documentation on the events and payloads below, see:
  // https://stripe.com/docs/elements/reference#element-on
  onChange?: (changeObject: Object) => void,
  onReady?: () => void,
  onFocus?: () => void,
  onBlur?: () => void,
};

injectStripe HOC

Components that need to initiate Source or Token creations (e.g. a checkout form component) can access stripe.createToken via props of any component returned by the injectStripe HOC factory.

Example

const StripeCheckoutForm = injectStripe(CheckoutForm);

The following props will be available to this component:

type FactoryProps = {
  stripe: {
    createToken: (tokenParameters: {type?: string}) => Promise<{token?: Object, error?: Object}>,
    // and other functions available on the `stripe` object,
    // as officially documented here: https://stripe.com/docs/elements/reference#the-stripe-object
  },
};

Development

Install dependencies:

yarn install

Run the demo:

yarn run demo

Run the tests:

yarn run test

Build:

yarn run build

We use prettier for code formatting:

yarn run prettier

Checks:

yarn run lint
yarn run flow

react-stripe-elements's People

Contributors

jenan-stripe avatar michelle avatar cweiss-stripe avatar tuxrace avatar indiesquidge avatar stephen avatar whatrocks avatar ezhlobo avatar jez avatar michelle-stripe avatar romainhuet avatar shaneosullivan avatar shaun-stripe avatar

Watchers

Tedde Lundgren avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.