0

How can I put this piece of code in only one of my React components?


<!--
  Create a button that your customers click to complete their purchase. Customize the styling to suit your branding.
-->
<button
  style="background-color:#6772E5;color:#FFF;padding:8px 12px;border:0;border-radius:4px;font-size:1em"
  id="checkout-button-sku_FAe7tbPK29byHW"
  role="link"
>
  Checkout
</button>

<div id="error-message"></div>

<script>
  var stripe = Stripe("pk_live_5PjwBk9dSdW7htTKHQ3HKrTd");
  var checkoutButton = document.getElementById(
    "checkout-button-sku_FAe7tbPK29byHW"
  );
  checkoutButton.addEventListener("click", function() {
    stripe
      .redirectToCheckout({
        items: [{ sku: "sku_FAe7tbPK29byHW", quantity: 1 }],
        successUrl:
          window.location.protocol + "//www.jobdirecto.com/jobConfirm",
        cancelUrl: window.location.protocol + "//www.jobdirecto.com/errorPage"
      })
      .then(function(result) {
        if (result.error) {
          var displayError = document.getElementById("error-message");
          displayError.textContent = result.error.message;
        }
      });
  });
</script>

At the moment it is in index.js (where all the other script tags are) and it works correctly, but it appears in all the pages. I want it to appear only in one component but I'm not sure where to put it.

Should I create a function and put inside there? or should I put it somehow below the render part?

1
  • 1
    You wouldn't add it as-is, you'd implement a click handler as a bound component function and update state appropriately. "Where" is largely irrelevant, although I'd keep the functionality separate from component functionality for easier testing and modification. Commented Jun 1, 2019 at 21:59

1 Answer 1

1

To make that a React component it would become something like this:

import React, { useState } from 'react';

function Button() {
  const stripe = Stripe('pk_live_5PjwBk9dSdW7htTKHQ3HKrTd');

  const [error, setError] = useState();

  const handleClick = () => {
    stripe
      .redirectToCheckout({
        items: [{ sku: 'sku_FAe7tbPK29byHW', quantity: 1 }],
        successUrl: window.location.protocol + '//www.jobdirecto.com/jobConfirm',
        cancelUrl: window.location.protocol + '//www.jobdirecto.com/errorPage'
      }).then((result) => {
        if (result.error) {
          setError(result.error.message);
        }
      });
  }

  return (
    <div>
      <button onClick={handleClick}>Checkout</button>
      {!!error && <div>{error}</div>}
    </div>
  );
}

export default Button;

Hope it helps you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.