@stripe/react-stripe-js#Elements JavaScript Examples

The following examples show how to use @stripe/react-stripe-js#Elements. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Stripe.jsx    From saasgear with MIT License 6 votes vote down vote up
StripeContainer = ({
  onSubmitSuccess,
  className,
  onGoBack,
  apiLoading,
  apiError,
  submitText,
}) => (
  <Elements stripe={stripePromise}>
    <StripeForm
      onSubmitSuccess={onSubmitSuccess}
      className={className}
      onGoBack={onGoBack}
      apiLoading={apiLoading}
      apiError={apiError}
      submitText={submitText}
    />
  </Elements>
)
Example #2
Source File: index.js    From subscription-use-cases with MIT License 6 votes vote down vote up
fetch('/config')
  .then((response) => response.json())
  .then((data) => {
    const stripePromise = loadStripe(data.publishableKey);

    ReactDOM.render(
      <React.StrictMode>
        <Elements stripe={stripePromise}>
          <App />
        </Elements>
      </React.StrictMode>,
      document.getElementById('root')
    );
  })
  .catch((error) => {
    console.error('Error:', error);
  });
Example #3
Source File: index.js    From react-elements-netlify-serverless with MIT License 6 votes vote down vote up
ReactDOM.render(
  <Elements stripe={stripePromise}>
    <CartProvider mode="checkout-session" stripe={stripePromise} currency="USD">
      <Router>
        <header>
          <Link to="/">Serverless Shopping Cart & Mobile Payments</Link>
        </header>

        <Switch>
          <Route path="/success">
            <Success />
          </Route>
          <Route path="/">
            <App />
          </Route>
        </Switch>
      </Router>
      <footer>
        <p>
          Based on an{' '}
          <a href="https://www.learnwithjason.dev/add-apple-pay-google-pay-to-jamstack-sites">
            episode of <em>Learn With Jason</em>
          </a>
          {' · '}<a href="https://www.netlify.com/blog/2020/05/21/learn-to-add-apple-pay-and-google-pay-to-react-websites/">read the tutorial</a>
          {' · '}<a href="https://github.com/stripe-samples/react-elements-netlify-serverless">
            source code
          </a>
        </p>
      </footer>
    </CartProvider>
  </Elements>,
  document.getElementById('root')
);
Example #4
Source File: App.js    From fireact with MIT License 6 votes vote down vote up
function App() {
	return (
		<Elements stripe={stripePromise}>
			<AuthProvider>
				<Router>
					<Switch>
						<AuthRouter exact path="/" component={Home} template={AppTemplate} title="My Accounts" />
						<AuthRouter exact path="/account/:accountId/images/edit/:imageId" component={ImageEdit} template={AccountTemplate} title="Edit Image" role="*" />
						<AuthRouter exact path="/account/:accountId/images/create" component={ImageCreate} template={AccountTemplate} title="Create Image" role="*" />
						<AuthRouter exact path="/account/:accountId/images" component={ImageList} template={AccountTemplate} title="Images" role="*" />
						<AuthRouter exact path="/account/:accountId/billing/plan" component={Plans} template={AccountTemplate} title="Select Plan" role="admin" allowInactive={true} />
						<AuthRouter exact path="/account/:accountId/billing/payment-method" component={PaymentMethod} template={AccountTemplate} title="Update Payment Method" role="admin" />
						<AuthRouter exact path="/account/:accountId/billing/delete" component={DeleteAccount} template={AccountTemplate} title="Delete Account" role="admin" />
						<AuthRouter exact path="/account/:accountId/users/change/:userId" component={UserRole} template={AccountTemplate} title="Change Role" role="admin" />
						<AuthRouter exact path="/account/:accountId/users" component={UserList} template={AccountTemplate} title="Users" role="admin" />
						<AuthRouter exact path="/account/:accountId/users/add" component={AddUser} template={AccountTemplate} title="Add User" role="admin" />
						<AuthRouter exact path="/account/:accountId/billing" component={PaymentList} template={AccountTemplate} title="Billing" role="admin" />
						<AuthRouter exact path="/account/:accountId/" component={Overview} template={AccountTemplate} title="Overview" role="*" />
						<AuthRouter exact path="/new-account" component={NewAccount} template={AppTemplate} title="Create New Account" />
						<AuthRouter exact path="/user/profile" component={UserProfile} template={AppTemplate} title="User Profile" />
						<AuthRouter exact path="/invite/:code" component={Invite} template={AppTemplate} title="View Invite" />
						<AuthRouter exact path="/user/profile/update-email" component={UpdateEmail} template={AppTemplate} title="Change Your Email" />
						<AuthRouter exact path="/user/profile/update-name" component={UpdateName} template={AppTemplate} title="Change Your Name" />
						<AuthRouter exact path="/user/profile/verify-email" component={VerifyEmail} template={AppTemplate} title="Verify Your Name" />
						<AuthRouter exact path="/user/profile/update-password" component={UpdatePassword} template={AppTemplate} title="Change Your Password" />
						<AuthRouter exact path="/user/profile/update-phone" component={UpdatePhone} template={AppTemplate} title="Change Your Phone Number" />
						<AuthRouter exact path="/user/profile/delete" component={DeleteUser} template={AppTemplate} title="Delete Your Account" />
						<AuthRouter exact path="/user/log" component={ViewLogs} template={AppTemplate} title="View Activity Logs" />
						<PublicRouter exact path="/signin" component={SignIn} template={PublicTemplate} title="Sign In" />
						<PublicRouter component={PageNotFound} template={PublicTemplate} title="Page Not Found" />
					</Switch>
				</Router>
			</AuthProvider>
		</Elements>
	);
}
Example #5
Source File: checkout.js    From jamstack-ecommerce with MIT License 6 votes vote down vote up
function CheckoutWithContext(props) {
  return (
    <ContextProviderComponent>
      <SiteContext.Consumer>
        {context => (
          <Elements stripe={stripePromise}>
            <Checkout {...props} context={context} />
          </Elements>
        )}
      </SiteContext.Consumer>
    </ContextProviderComponent>
  )
}
Example #6
Source File: AddBalanceDialog.js    From react-saas-template with MIT License 6 votes vote down vote up
function Wrapper(props) {
  const { open, onClose, onSuccess } = props;
  return (
    <Elements stripe={stripePromise}>
      {open && (
        <AddBalanceDialog open={open} onClose={onClose} onSuccess={onSuccess} />
      )}
    </Elements>
  );
}
Example #7
Source File: index.js    From rysolv with GNU Affero General Public License v3.0 6 votes vote down vote up
export function App() {
  return (
    <Elements stripe={stripePromise}>
      <StylesProvider generateClassName={generateClassName} jss={jss}>
        <MuiThemeProvider theme={muiTheme}>
          <ViewSize>
            <Main />
            <GlobalStyles />
          </ViewSize>
        </MuiThemeProvider>
      </StylesProvider>
    </Elements>
  );
}
Example #8
Source File: index.js    From jamstack-ecommerce with MIT License 6 votes vote down vote up
export default function Home() {
  return (
    <div>
      Hello world!
      
      <Elements stripe={stripePromise}>
        <CheckoutForm />
      </Elements>
    </div>
  )
}
Example #9
Source File: checkout.js    From muffinsplantshop with BSD Zero Clause License 6 votes vote down vote up
Checkout = ({ location }) => {
    const promise = loadStripe('pk_test_51HZH64Ftxr5x8qZUweU2PctrS7eRgFIRYYMjnZsiRTDLwQqd8yJ2bZxbFnxv3lD2AvwPx6vvpZkXKxTbJhWsKJhv00MpHObXp8');

    return (
        <Layout location={location}>
            <SEO title="Checkout" />
            <Elements stripe={promise}>
                <CheckoutForm />
            </Elements>
        </Layout>
    );
}
Example #10
Source File: Render.jsx    From dineforward with MIT License 5 votes vote down vote up
function App() {
  const [config, setCOnfig] = useState();
  const [cart, setCart] = useState();
  const [status, setStatus] = useState();
  useEffect(() => {
    (async () => {
      // Fetch config object
      // const config = await fetch('/api/stripe/config').then(res => res.json());
      const config = {};
      config.stripePromise = loadStripe('pk_test_gTcHufxzRAofRn6BmYNsJWJ100KT6rF8fd');
      setCOnfig(config);
      // Fetch the products from the API.
      // const res = await fetch('/api/products').then(res => res.json());
      // const products = res.data;
      // const items = products.map(product => ({
      //   price: product.skus.data[0].price,
      //   quantity: randomQuantity(1, 2),
      //   type: 'sku',
      //   id: product.id,
      //   name: product.name,
      //   parent: product.skus.data[0].id,
      //   attributes: product.skus.data[0].attributes,
      // }));

      const items = [];
      const { paymentIntent } = await fetch('/api/payment_intents', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          currency: config.currency,
          items,
        }),
      }).then(res => res.json());
      setCart({
        currency: config.currency,
        items,
        total: items.reduce((sum, item) => sum + item.quantity * item.price, 0),
        paymentIntent,
        setStatus,
      });
    })();
  }, []);

  return (
    <Elements stripe={config?.stripePromise ?? null}>
      <main
        id="main"
        className={cart ? (status ? `checkout ${status.class}` : 'checkout') : 'loading'}
      >
        <Checkout config={config} cart={cart} />
        <PaymentResult message={status?.message} />
      </main>
      <Aside cart={cart} />
    </Elements>
  );
}
Example #11
Source File: App.js    From turqV2 with GNU General Public License v3.0 5 votes vote down vote up
function App() {
  return (

  <Elements stripe={stripePromise}>
    <BrowserRouter>
      <ScrollToTop />
      <div className="App">
        <Helmet>
            <meta charset="utf-8" />
            <meta name="description" content="Make direct democracy viable by enabling citizens to draft and submit their own legislation." />
            <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
            <title>Turq</title>
        </Helmet>
        <ToastContainer
          closeOnClick
          position="top-center"
          autoClose={5000}
          hideProgressBar={true}
          draggable
          newestOnTop={false}
        />
      </div>

      <Switch>
        <Route path={constants.HOME_PAGE_URL} exact component={Home} />
        <Route path={constants.ABOUT_PAGE_URL} component={About} />
        <Route path={constants.DRAFTER_PAGE_URL} component={Drafter} />
        <Route path={constants.LOGIN_PAGE_URL} component={Login} />
        <Route path={constants.REGISTER_PAGE_URL} component={Register} />
        <Route path={constants.CONTEST_PAGE_URL} exact component={ContestList} />
        <Route path={constants.CONTEST_PAGE_URL + "/:id"} component={Contest}/>
        <Route path={constants.LEGISLATION_PAGE_URL + "/:id"} component={Legislation}/>
        <Route path={constants.THANKYOU_URL} component={PaymentThankyou} />
        <PrivateRoute path={constants.CHECKOUT_PAGE_URL} component={Checkout}/>
        <PrivateRoute path={constants.EDITOR_PAGE_URL + "/contest"}  exact component={ContestEditor}/>
        <PrivateRoute path={constants.EDITOR_PAGE_URL + "/contest/:id"}  exact component={ContestEditor}/>
        <PrivateRoute path={constants.EDITOR_PAGE_URL + "/legislation"} exact component={LegislationEditor}/>
        <PrivateRoute path={constants.EDITOR_PAGE_URL + "/legislation/:id"} exact component={LegislationEditor}/>
      </Switch>

    </BrowserRouter>
  </Elements>
  );
}
Example #12
Source File: Stripe.js    From greenbook with MIT License 5 votes vote down vote up
Striper = (props) => {
	return (
		<Elements stripe={stripePromise}>
			<CheckoutForm />
		</Elements>
	);
}
Example #13
Source File: App.js    From create-magic-app with MIT License 5 votes vote down vote up
function App() {
  // Create a hook to check whether or not user has lifetime acess
  const [lifetimeAccess, setLifetimeAccess] = useState(false);
  // Create a hook to help us determine whether or not the  user is logged in
  const [user, setUser] = useState();

  // If isLoggedIn is true, set the UserContext with user data
  // Otherwise, set it to {user: null}
  useEffect(() => {
    setUser({ loading: true });
    magic.user.isLoggedIn().then((isLoggedIn) => {
      return isLoggedIn
        ? magic.user.getMetadata().then((userData) => setUser(userData))
        : setUser({ user: null });
    });
  }, []);

  return (
    <Router>
      <Switch>
        <UserContext.Provider value={[user, setUser]}>
          <LifetimeContext.Provider value={[lifetimeAccess, setLifetimeAccess]}>
            <Layout>
              <Route path="/" exact component={Home} />
              <Route path="/premium-content" component={PremiumContent} />
              <Route path="/signup" component={SignUp} />
              <Route path="/login" component={Login} />
              <Route path="/profile" component={Profile} />
              <Route
                path="/payment"
                render={(props) => {
                  return (
                    <Payment
                       Elements={Elements}
                      PaymentForm={PaymentForm}
                      promise={promise}
                    />
                  );
                }}
              />
            </Layout>
          </LifetimeContext.Provider>
        </UserContext.Provider>
      </Switch>
    </Router>
  );
}
Example #14
Source File: PaymentWraper.jsx    From real-estate-site with MIT License 5 votes vote down vote up
render() {
    return (
      <Elements stripe={stripePromise}>
        <CheckoutForm amountInCents={this.props.amountInCents} />
      </Elements>
    );
  }
Example #15
Source File: App.js    From shopping-cart-fe with MIT License 5 votes vote down vote up
function App() {
	window.addEventListener('load', () => {
		function handleNetworkChange(event) {
			// delete this comment
			if (navigator.onLine) {
				document.getElementById('offline-notification').style.display = 'none';
			}
			else {
				document.getElementById('offline-notification').style.display = 'flex';
			}
		}
		window.addEventListener('online', handleNetworkChange);
		window.addEventListener('offline', handleNetworkChange);
	});

	//TODO: Create a useEffect to get the Stripe Account for store owner dynamicly
	const stripePromise = loadStripe('pk_test_VHc4fOD3byWy85jOWOYLijhH00OmL57YuX', {
		stripeAccount: 'acct_1H6LilIrVDEEa5AF'
	});
	return (
		<div>
			<Switch>
				<Elements stripe={stripePromise}>
					<PublicRoute path="/register" component={WrappedRegistrationForm} />
					{/* {Import WelcomeScreen} */}
					<PublicRoute path="/welcome" component={WelcomeScreenForm} />
					<PublicRoute path="/brandview" component={BrandView} />
					<PublicRoute path="/colorpicker" component={ColorPicker} />
					{/* Onboarding reformatted Above */}
					<PublicRoute path="/update" component={Update} />
					<PublicRoute exact path="/" component={LoginForm} />
					<PrivateRoute path="/inventory" component={Inventory} />
					{/* Profile View */}
					<PrivateRoute path="/profileview" component={ProfileView} />
					<PublicRoute path="/resetpassword" component={ResetPasswordForm} />
					<PublicRoute path="/setnewpassword" component={SetNewPasswordForm} />
					<PublicRoute path="/store/:id" component={StoreView} />

					<PublicRoute path="/cart" component={CartView} />
					<PrivateRoute path="/api/auth/stripe/token" component={StripeConfirmAccount} />
					<PublicRoute path="/savecart" component={SaveCartMain} />
					<PrivateRoute path="/createstore" component={CreateStoreForm} />
					<PrivateRoute path="/addlogo" component={AddLogoForm} />
					<PrivateRoute path="/createitem" component={CreateProductView} />
					<PrivateRoute path="/dashboard" component={Home} />
					<PrivateRoute path="/updateitem/:id" component={UpdateItem} />
					<PrivateRoute path="/order/:id" component={OrderDetailsView} />
					<PublicRoute path="/product/:id" component={Single} />

					<PublicRoute path="/success/:id" component={CheckoutSuccessView} />
					<PrivateRoute path="/account" component={Account} />
				</Elements>
			</Switch>
			<div
				id="offline-notification"
				style={{
					position: 'fixed',
					bottom: '0px',
					width: '100vw',
					height: '4vh',
					textAlign: 'center',
					backgroundColor: '#ff6663',
					justifyContent: 'space-around',
					alignItems: 'center',
					color: 'white',
					fontSize: 'medium',
					display: 'none'
				}}
			>
				Offline Mode
			</div>
		</div>
	);
}
Example #16
Source File: hire-remotely.js    From remotebond-remote-jobs with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
NewJobPage = ({ paymentIntent }) => {
  return (
    <Elements stripe={stripePromise}>
      <>
        <NextSeo
          title={`Create a new remote job post`}
          description="Start hiring remotely, post a new remote job and find the most qualified people for your next remote position."
          canonical={`https://remotebond.com/hire-remotely`}
          openGraph={{
            url: `https://remotebond.com/hire-remotely`,
            title: `Create a new remote job post`,
            description: `Start hiring remotely, post a new remote job and find the most qualified people for your next remote position.`,
          }}
        />
        <BreadcrumbJsonLd
          itemListElements={[
            {
              position: 1,
              name: "remotebond.com",
              item: "https://remotebond.com",
            },
            {
              position: 2,
              name: "Hire Remotely",
            },
          ]}
        />
        <Banner message={`Launch deal! Base job ad is now priced at $25`} />
        <div className="relative overflow-hidden bg-black">
          <div className="max-w-screen-xl mx-auto py-16 px-4 sm:px-6 lg:py-12 lg:px-8">
            <div>
              <h1 className="text-center text-3xl leading-9 font-extrabold text-white">
                Hire remotely
              </h1>
              <h2 className="text-rb-gray-4 text-center w-full">
                Create your remote job post and reach remote workers all around
                the world.
              </h2>
            </div>
          </div>
        </div>
        <JobPostForm paymentIntentSSR={paymentIntent} />
      </>
    </Elements>
  )
}
Example #17
Source File: App.js    From tutorial-code with MIT License 5 votes vote down vote up
function App() {
  return (
    <Elements stripe={stripePromise}>
      <HomePage />
    </Elements>
  );
}
Example #18
Source File: App.js    From tutorial-code with MIT License 5 votes vote down vote up
function App() {
  return (
    <Elements stripe={stripePromise}>
      <HomePage />
    </Elements>
  );
}
Example #19
Source File: App.js    From tutorial-code with MIT License 5 votes vote down vote up
function App() {
  return (
    <Elements stripe={stripePromise}>
      <HomePage />
    </Elements>
  );
}
Example #20
Source File: cart.test.js    From shopping-cart-fe with MIT License 4 votes vote down vote up
describe('Render Tests', () => {
	//Needed to repliate stripe
	const stripePromise = loadStripe('pk_test_VHc4fOD3byWy85jOWOYLijhH00OmL57YuX', {
		stripeAccount: 'acct_1H6LilIrVDEEa5AF'
	});

	const cartContents = [
		{
			images: [
				'https://res.cloudinary.com/dnsl4nbz4/image/upload/v1595381636/Products/gml8p0moezrwcwc1az0v.jpg',
				''
			],
			price: 100,
			productId: '5f1797a53e2aad0004e78a9e',
			productName: 'Cool Shirt',
			quantity: 1,
			variantDetails: [ { _id: '5f1797a53e2aad0004e78a9f', option: 'small', price: 100 } ]
		}
	];

	const store = {
		logo: 'https://res.cloudinary.com/dnsl4nbz4/image/upload/v1595295400/zqqf2ualihvj8xuohmgn.png',
		color: '#eb144c'
	};

	const totalPrice = (arr) => {
		return arr.reduce((sum, item) => {
			return sum + item.price * item.quantity;
		}, 0);
	};

	const paymentPayload = {
		price: 100,
		clientID: 'acct_1H7ALoISbGMo70op'
	};

	const orderPayload = {
		orderItem: [
			{
				product: '5f1797a53e2aad0004e78a9e',
				quantity: 1,
				chosenVariant: {
					price: 100
				}
			}
		]
	};

	const getStoreID = '5f1645a717a4730004f569c3';

	test('Render Test for CartView', () => {
		renderWithProviders(
			<Elements stripe={stripePromise}>
				<CartView />
			</Elements>
		);
	});

	test('Render test for CartTable', () => {
		<Elements stripe={stripePromise}>
			<CartTable />
		</Elements>;
	});

	test('Renders Table & Item', () => {
		const { getByTestId } = renderWithProviders(
			<Elements stripe={stripePromise}>
				<CartTable cartContents={cartContents} totalPrice={totalPrice} store={store} />
			</Elements>
		);
		expect(getByTestId('CartTable')).toHaveTextContent('Product');
		expect(getByTestId('productName')).toHaveTextContent('Cool Shirt');
		expect(getByTestId('price')).toHaveTextContent('$100');
	});

	test('Total Cost is Working', () => {
		const { getByTestId } = renderWithProviders(
			<Elements stripe={stripePromise}>
				<CartTable cartContents={cartContents} totalPrice={totalPrice} store={store} />
			</Elements>
		);
		expect(getByTestId('total')).toHaveTextContent('$100');
	});
});