Add Stripe payment to your React Project

Fadi Tillman
2 min readMar 21, 2021

A payment method is an essential component of E-commerce. For a beginner web developer, the documentation can be intimidating. Here is where a tutorial can help simplify things. I highly recommend going back and reading the documentation to learn about the different functionality. For this tutorial, I will be using one of my react past projects as a test case. I will strictly focus on stripe and exclude Axios setup.

I / Install stripe packages

npm install @stripe/stripe-jsnpm install @stripe/react-stripe-js @stripe/stripe-js

II / Create a stripe account

www.stripe.com

1/In your dashboard go to “developers” in the left panel under the Home icon
2/ click on “API keys”
3/ In the new dashboard under “Standard Key”
copy the “publishable key” (I made the choice to hide this key just for an extra layer of security)

III/ Import stripe and wrap your target page

A/ Import Stripe

//App.jsimport {loadStripe} from '@stripe/stripe-js';import {Elements} from '@stripe/react-stripe-js';const stripePromise  =  loadStripe('publishable_key');
(use await for async function)

B/ wrap payement page in Element

//App.jsimport {BrowserRouter as Router, Switch, Route}function App() {
return (
<Router>
<div className="App">
<Switch>
</Route>
<Route path="/payment">
<Header/>
<Elements stripe={stripePromise}>
<Payment/>
</Elements>
</Route>
</Switch>
</div>
</Router>
);
}
export default App;

IV/ Import Stripe and create card Element

//Payement.jsimport "./Payment.css"import {CardElement,Elements,useStripe,useElements,} from '@stripe/react-stripe-js';function Payment() {const stripe = useStripe();const elements = useElements();const handleSubmit = async (event) => {
event.preventDefault();
const {error, paymentMethod} = await stripe.createPaymentMethod({
type: 'card',
card: elements.getElement(CardElement),
});
};
return ( <div className="payment-part">
<div className="payment-header">
<h3> payment method</h3>
<div className="payment-infos"></div>
<form onSubmit={handleSubmit}>
<CardElement />
<button type="submit" disabled={!stripe}>
Pay
</button>
</form>
<div className='price'>
<strong> Total: </strong>
</div>
</div>
</div>
</div>
)};export default Payment

V / CSS

//Payement.css .payement-infos {
display: 0.8;
}
.payment-part{
margin: 0 20px ;
display: flex;
padding: 21px;
border-bottom: 2px solid lightgray;
}.payment-header{
flex: 0.2;
}

Et Voila! You can add Stripe payment to your React App.

--

--