I need to create token with Stripe.js in React JS, but I can't find any easy way. In node.js I would do something like this:
stripeClient.tokens.create({
card: {
number: '4242424242424242',
exp_month: 12,
exp_year: 2050,
cvc: '123'
}
But the Stripe npm module doesn't work for me in React JS. I'm getting error:
Cannot resolve module 'child_process'
So since this is node pibrary obviously, I would like to use
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
But I'm not sure what should be the best practice to implement external libraries in React
You can just go ahead and add it like any other client side library, like you might have done in the past.
Include this script tag:
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
Then use the global that it exposes inside your code.
import React from 'react';
// we didn't have to import stripe, because it's already
// in our global namespace.
Stripe.setPublishableKey('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
It's not as clean as being able to require it from NPM, but it will work just fine.
For those who are looking for guidance when using Stripe in React: Accept Stripe Payments with React and Express is an article with a straight forward implementation of Stripe in React (create-react-app) and a minimal Express server that handles your payment requests and forwards them to the Stripe platform. The article keeps the boilerplate to a minimum and comes with an open source project that you can simply try out on your own.
Switch to BrainTree
They support a client-side NPM package which can be used with create-react-app (Webpack / Browserify): https://developers.braintreepayments.com/guides/client-sdk/setup/javascript/v3#npm
npm install --save braintree-web
Unfortunately Stripe and React don't fit well together
The version of Stripe on NPM is for server-side use only; so even if you Webpack / Browserify the library (as provided by create-react-app), then client-side features for configuring the public-key and tokenizing the credit-card information are missing.
For the client-side, Stripe prefers "stripe.js" to be used from an external URL: https://js.stripe.com/v3/. Unfortunately, external URLs aren't well-suited for create-react-app - for example, ES6 import can't be used, and the external file is not bundled by Webpack. Furthermore, version (v3) forces users to use an elements method and query the DOM (basically going against React).
You can add direct link in html file but the other side of this, It will load every time even if their is no requirement.
So i would suggest you to add stripe library via your code to stay with lazy lodaing concept.
const script = document.createElement("script");
script.src = "https://js.stripe.com/v3/";
script.async = true;
document.body.appendChild(script);
Then
Stripe = Stripe('your keys').
After this Stripe.createToken('add any of your card element').then(setOutcome)
Please try this apporach...
In public index.html
<script src="https://js.stripe.com/v2/"></script>
<title>React App</title>
</head>
and in the component
componentDidMount() {
if(window.Stripe.setPublishableKey){
window.Stripe.setPublishableKey('pk_test_LkK8cMTD4YXUImjZquRnAqXb');
}
}
Its working for me...
Then in calling Stripe methods you just need to do:
!window.Stripe.card.validateCardNumber(
Related
I am trying to figure out how to add external JS to a React app without adding it to the HTML file in a script tag. The reason for this is that I have one component that needs access to an external script, but I can only access it as a global variable by adding /*global <variabe name>*/ at the top of the component that needs it (as far as I know), which is not ideal.
I'm basically looking for an equivalent to
const someScript = <script type="text/javascript" src="some url"></script>
but in a way that actually works 😀
This script is not needed when the app initially loads and could come in async.
You have to install react script
Use npm install react-script-tag
And Add import which is
‘import ScriptTag from 'react-script-tag';’
And then you can use it
I have a web application developed in php, jquery and other technologies ... I need to add React to an existing web application only in a part of the application, I would like to know what would be the recommended configuration of webpack + babel
in order to do what you want, you need to get a bundle out of your react code (that is done with webpack, which you're already using).
Only instead of just calling React.render(...) in your index.js, you'll do something like so:
function initMyReactComponent(selector, props = {}) {
ReactDOM.render(
<MyComponent {...props}/>,
document.querySelector(selector),
);
}
and in your php code, you add the bundle via a <script> tag, and use the initMyReactComponent method in site.
React is very easy to use in that sense, because it can mount itself anywhere, anytime, all you have to do is tell it when to do it!
In webpack.config file declared a variable to read in application.
let BASEURL = "http://127.0.0.1:8090";
with this approach I am not able to update BASEURL after npm run build. Every time I want to generate a new build for each environment if BASEURL changes.
Is there any way to build once and deploy build file in multiple environments with minimal changes?
Tl;dr: use AJAX and have the config either in react context or in a global variable.
Detailed answer:
It is indeed as you state, after the application is built with npm run build, the environment variables become hardwired and cannot be changed.
The official statement of create-react-app is it does not support the build once deploy many principle. From https://create-react-app.dev/docs/adding-custom-environment-variables/ :
The environment variables are embedded during the build time. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime.
However, there are ways of achieving the principle, just a bit more complicated. The idea is, you need to get the value of a variable at runtime from an external source, e.g. AJAX. In more details, possible solutions may be (but are not limited to) following:
1. server-side placeholder replacement
This is a solution proposed by create-react-app in https://create-react-app.dev/docs/title-and-meta-tags/#injecting-data-from-the-server-into-the-page, introducing a custom placeholder and replacing it with the data on the server, before it is rendered to clients.
<!doctype html>
<html lang="en">
<head>
<script>
window.SERVER_DATA = __SERVER_DATA__;
</script>
While this works, it introduces a major overhead, because it leaves the whole backend implementation up to you. Depending on your tech stack, this may be very easy or also very complicated to implement.
2. a dynamic <script> that assigns variable values
A solution proposed in https://www.cotyhamilton.com/build-once-deploy-anywhere-for-react-applications/ utilizes the dynamic nature of javascript. In the dynamically downloaded config.js file, a value is assigned to the variable. In the rest of the React code, the variable is read and used. You can change the config.js file any time, without the need of recompiling the react app.
// public/config.js
const apiUrl = 'localhost:1337';
const env = 'development';
<!-- public/index.html -->
<script src="%PUBLIC_URL%/config.js"></script>
<script>
window.config = { apiUrl, env };
</script>
The main downside is that this does not support TypeScript, and your IDE or linter may complain that apiUrl and env are not defined. Especially in bigger projects, this approach may be hard to maintain.
3. dynamic config with AJAX, with TypeScript support
Based on the 2nd solution, this article https://profinit.eu/en/blog/build-once-deploy-many-in-react-dynamic-configuration-properties/ describes in a great detail how to best achieve the build once deploy many principle with create-react-app and what are pros and cons.
It proposes downloading the dynamic config as a JSON with AJAX. The main caveat is to make sure that the dynamic config is downloaded BEFORE some code tires to use it. In the context of React lifecycle, there are two ways of how to achieve this.
3.1 global variable
Download the dynamic config JSON from globalConfigUrl, store it in a global variable, and only then render the React app. Example in TypeScript:
// index.tsx:
import axios from "axios";
import React, {ReactElement} from "react";
import App from "./App";
import {globalConfig, globalConfigUrl} from "./configuration/config";
axios.get(globalConfigUrl)
.then((response) => {
globalConfig.config = response.data; // THIS IS THE IMPORTANT LINE
return <App />;
})
.catch(e => {
return <p style={{color: "red", textAlign: "center"}}>Error while fetching global config</p>;
})
.then((reactElement: ReactElement) => {
ReactDOM.render(
reactElement,
document.getElementById("root")
);
});
Full working example: https://codesandbox.io/s/build-once-deploy-many-global-config-object-dvpzr
3.2. React context
Wrap your <App> component with a react context provider containing the configuration (with undefined or some default value). Fetch the configuration first time App is rendered and then save its value to the context. React will take care of the rest and will propagate the value change!
Full working example: https://codesandbox.io/s/build-once-deploy-many-react-context-7lk7g
The basic idea is this. Check the article above / working example for all details:
// App.tsx
import {useConfig} from "./configuration/useConfig";
// ... in the method:
const { setConfig } = useConfig(); // the `useConfig` is a custom hook, wrapping a React context. See the full working example for all details
useEffect(() => {
axios
.get(dynamicConfigUrl)
.then((response) => {
setConfig(response.data);
})
}, [setConfig]);
We have chosen the react JS 0.14.8 for front end because it supports IE 8 browser but Is Node JS or JSX is necessary for React JS development or we can create components without Node JS or Jsx
Yes you can create ReactJs app without nodejs and jsx.
But why you should use JSX?
JSX provides a very clean way to declare your UI component.
You can use your familiar html syntax to declare your user interface.
JSX gets trans-piled and converted to light weight objects representing ui elements.
e.g
You can use following way to declare a react js via
1.jsx
const App = () => {
return (
<div><h1>Welcome to React</h1></div>
);
}
or
2.without jsx
const App = function App() {
return React.createElement(
"div",
null,
React.createElement(
"h1",
null,
"Welcome to React"
)
);
};
You can guess which one is easy to write.
Why should I use nodejs to build browser projects?
nodejs is never required for running websites on browser.
But nodejs ecosystem provides you thousands of npm modules to use in your projects without reinventing them just for your projects.
Without nodejs you could have used cdn providers and added <script> tag to use any library. But with the use of module bundlers and static assets generator such as browserify and webpack you can leverage the powser of nodejs ecosystem directly in your web project( which does not require nodejs runtime environment but rather run in browser).
Below snippet use <script> tag to make reactjs available without nodejs.
const App = () => {
return (
<div><h1>Welcome to React</h1></div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app">
</div>
Is node js required for React JS?
Let me split the answer into 2 parts:
In Production:
Server Side: Not needed unless you are using Node.js to create a web server and server your ReactJS files.
Client Side: Only browser is enough.
In development:
Server Side: Needed to download react libraries and other dependencies using NPM. Needed by webpack to create production bundles.
Client Side: Only browser is enough.
Is JSX required for React JS?
Developer can use HTML tags directly inside javascript if JSX(javascript + XML tags) is used. otherwise it becomes difficult to write code as well as to understand the code.
Hope this answer helps, Thank you
They're not strict requirements; you can include react with a script tag and use React.createElement.
That said, almost everyone uses node.js for development tooling and uses jsx. You can use any language for your api server, but you'll use a node.js server in development most of the time.
Usage:
require('node-jsx').install()
If you want to use a different extension, do:
require('node-jsx').install({extension: '.jsx'})
If you want to couple with an additional transform (such as CoffeeScript), do:
var coffee = require('coffee-script');
require('node-jsx').install({
extension: '.coffee',
additionalTransform: function(src) {
return coffee.compile(src, {
'bare': true
});
}
});
If you want to use ES6 transforms available in the JSX tool
require('node-jsx').install({harmony: true})
I am working on an isomorphic react project and am attempting to use the Stripe node SDK (vs their REST API) within a Redux module. When Webpack builds the project I get the error: Module not found: Error: Cannot resolve module 'child_process'. I know this is a node only module, so I cannot use it on the browser (I only want Stripe API calls to originate on the server-side), I just don't know how to ensure that the Stripe node_module is not packaged in to the browser app.js file.
While I am importing the stripe module in the redux module, on the JSX side, I am only importing the IStripe interface from the stripe.model and the getPlansList dispatcher from my stripe redux module.
So my question is how does one use node-only modules within an isomorphic React project? Do I need to run a separate server-only node process that handles my Stripe calls? Or is it possible to contain this functionality within my isomorphic app?
Thanks!
Look at the issue, you should not run stripe-node in browser.
You can setup alias in webpack config:
{
resolve: {
alias: {
'stripe': './src/stripe-browser'
}
}
}
If you don't need to use Stripe in browser, you can just create an empty file stripe-browser as a stub for API.
If you are going to use API in browser, you have to create an adapter to Stripe.js client-side library.