Skip to content
Sandny Blog
  • Home
  • Java
  • JavaScript
  • AWS
  • Embedded
  • About
add styles to stripe elements JavaScript

How to add styles to stripe elements without using…

  • June 29, 2021June 29, 2021
  • by Coder Kai

Stripe is a great way to make payments for your web or mobile platforms. Being a full service payment platform, Stripe also gives you a variety of SDKs to implement your backend and frontend code with the best compliance options. In this tutorial you will learn how to add styles to stripe elements if you don’t want to use existing styles of the card input.

1. Adding elements input to your web

First you will need to create a stripe account and get its public secret key to initialise authentication for payments. If you have that you will need to wrap your payment component with initialised Elements provider component.

import React from "react";
import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";

export interface CreateCardPaymentProps {
  onCreatePaymentMethod: (id: string) => void;
}

const stripePromise = loadStripe(
  "pk_test_k3jL***"
);

const CreateCardPayment: React.FC<CreateCardPaymentProps> = ({ onCreatePaymentMethod }) => {
  return (
      <Elements stripe={stripePromise}> 
        <CreateCardPayment onSuccessCard={onCreatePaymentMethod} />
      </Elements>
  );
};

export default CreateCardPayment;

Here Elements acts as the stripe provider. Note that this needs to provided in a higher order component so you can probably define in app root component as well. But if you dont need elsewhere you can declare it in the immediate parent component.

2. Add styles to stripe elements

If you need to fully customise the input, you cannot use the CardElement the component as explained in the examples.
Instead you can use following components.

  1. CardNumberElement – Enter card number Ex: 4242 4242 4242 4242
  2. CardExpiryElement – Expiry number Ex: 11/22
  3. CardCvcElement – CVC of the card Ex: 111
  4. Card holder name – Use an input with similar styles of the above inputs Ex: John Doe

From above you need to first create the card input components. First we will take the card number.

<CardNumberElement
   options={{
   style: {
     base: inputStyle,
   },
 }}
/>

const inputStyle = {
      iconColor: '#c4f0ff',
      color: '#ff0',
      fontWeight: '500',
      fontFamily: 'Roboto, Open Sans, Segoe UI, sans-serif',
      fontSize: '16px',
      fontSmoothing: 'antialiased',
      ':-webkit-autofill': {
        color: '#fce883',
      },
      '::placeholder': {
        color: '#87BBFD',
      },
}

The UI will look like following which give you only an input field. It doesnt look good but we can give the styles we need using the next steps.

add styles to stripe elements

Apart from base there are several other styles tags you can use with options params.

:hover
:focus
::placeholder
::selection
:-webkit-autofill
:disabled, available for all Elements except the paymentRequestButton Element.
::-ms-clear, available for the cardNumber, cardExpiry, and cardCvc Elements. Inside the ::-ms-clear selector, the display property can be customized.

Also you can customise following fields other than base for error or invalid inputs.

  • base, base variant—all other variants inherit from these styles
  • complete, applied when the Element has valid input
  • empty, applied when the Element has no customer input
  • invalid, applied when the Element has invalid input

You can refer it from API https://stripe.com/docs/js/appendix/style

3. Adding borders and make it looks like other inputs

This will give you how to style the input component for the card number. To add a border a any other styles around this, you can wrap this inside a wrapper div component

<CardInputWrapper>
    <CardNumberElement
      options={{
        style: {
          base: inputStyle,
        },
      }}
    />
</CardInputWrapper>

const CardInputWrapper = styled.div`
  border: 2px solid #00f;
  border-radius: 8px;
  padding: 20px 4px;
`;
add styles to stripe elements

You can do the same for the CVV and Expiry code as shown in the above image.

4. Create Card payment using the CardNumberElement

Then you can insert the payment submit the card details using the card number input you have provided as follows. When you create the element with card number, it will take CVC and Expiry date by default. But you have to add the name of the card as a param to the create payment method input.


import {
  useElements,
  useStripe,
  CardNumberElement,
  CardExpiryElement,
  CardCvcElement,
} from "@stripe/react-stripe-js";

export interface CreateCardPaymentProps {
  onSuccessCard: (id: string) => void;
}

export const CreateCardPayment: React.FC<CreateCardPaymentProps> = ({onSuccessCard}) => {
  const [name, setName] = useState("");
  const elements = useElements(); // use element provider state
  const stripe = useStripe(); // stripe sdk

  const onSubmit = async () => {
    if (!stripe || !elements) {
      return;
    }
    // card number element as the card element
    const cardNumberElement = elements?.getElement(CardNumberElement);

    if (cardNumberElement) {
      const {error, paymentMethod} = await stripe?.createPaymentMethod({
        type: 'card',
        card: cardNumberElement,  // pass as card
        billing_details: {
          name, // name of the user
        },
      });

      if (!error && paymentMethod?.id) {
        onSuccessCard(paymentMethod.id);
      } else {
        onError();
      }
    }
  };
}

return (
 ...
    <CardInputWrapper>
      <CardNumberElement
        options={{
          style: {
            base: inputStyle,
          },
        }}
      />
   </CardInputWrapper>
  ...

  <button onClick={onSubmit}>Pay with card</button>
);

With above code you can make the card payment using the card number elements and get the payment method id for your payment intent.

You can refer more details on stripe inputs from following references:

React Example: https://stripe.com/docs/stripe-js/react
Create Payment Method: https://stripe.com/docs/js/payment_methods/create_payment_method
Styles: https://stripe.com/docs/js/appendix/style

If you have any question leave a comment below and I will improve above post.

How to use Typescript with arrays
How to fetch data with useEffect
Coder Kai
A humble developer
CardElement react.js Stripe.js

Related articles

Multiple refs for an array of React Elements
Using multiple refs for an…
Immutable and Mutable Values in Javascript
07. Immutable and Mutable Values…
wrapper objects in javascript
06. Wrapper objects in Javascript
globals undefined and null values in javascript
05 Global, null and undefined…
Javascript Booleans and Equality
04. Javascript Guide Booleans and…
How to add Chakra UI Animations
Chakra UI Animations
SSL Websocket using Nginx Proxy
SSL Websocket proxy with Nginx…
Change python version correctly
Python is not setting correct…
optimize React.js load time
How to optimize React.js app…
Multiple refs for an array of React Elements
How to use IntersectionObserver to…
Multiple refs for an array of React Elements
How to dismiss dropdowns when…
Javascript guide Strings
03. Javascript Guide – Strings
How to fetch data with useEffect
How to fetch data with…
Typescript
How to use Typescript with…
how to optimize react-native map view
How to optimize react-native map…
debounce with react hooks
Avoid multiple clicks using debounce…
Numbers inJavascript
02. Javascript Guide – Numbers
Introduction to Javascript
01. Javascript Guide – Introduction…
Nginx Load Balancer with docker…
Create React App Using npx

Categories

  • android 3
  • Apollo Client 1
  • AWS 8
    • AppSync 5
    • EC2 1
    • EKS 1
    • Route53 1
    • S3 1
  • AWS Amplify 1
  • Chakra UI 1
  • Docker 1
  • Embedded 1
  • EmberJS 1
  • FCM 1
  • Godaddy 1
  • GraphQL 3
  • ios 1
  • Jasper 1
  • Java 10
    • Java 11 1
    • Java 14 1
  • JavaEE 2
  • JavaScript 39
    • Express.js 4
    • Javascript Guide 7
    • Node.js 3
    • react-native 4
    • React.js 17
    • Typescript 1
  • Kubernetes 1
  • machine learning 1
  • Maven 2
  • OCaml 3
  • PostgreSQL 1
  • Python 2
  • react-native 4
  • ReactJS 3
  • sass 1
  • Server 6
  • spark 1
  • Terraform 2
  • Ubuntu 4
  • Uncategorized 1
  • webpack 2

Recent Comments

  • Pamela587 on Chakra UI Animations
  • Alicia1760 on Chakra UI Animations
  • vneuweluso on How to add styles to stripe elements without using CardElement

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Archives

  • October 2022 3
  • September 2022 7
  • May 2022 1
  • December 2021 1
  • August 2021 1
  • July 2021 6
  • June 2021 3
  • February 2021 1
  • July 2020 1
  • December 2019 5
  • November 2019 6
  • October 2019 3
  • August 2019 1
  • March 2019 1
  • February 2019 1
  • January 2019 2
  • December 2018 1
  • September 2018 2
  • August 2018 1
  • June 2018 1
  • February 2018 1
  • November 2017 2
  • October 2017 5
  • September 2017 1
  • June 2017 1
  • May 2017 10
Sandny Blog space
Theme by Colorlib Powered by WordPress