Is node js and JSX required for React JS - reactjs

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})

Related

how to configure react + webpack + babel on an existing website with a different technology

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!

Setting up webpack to export to set folder

I'm working on an old project still running jquery for frontend, java spring for the backend, and maven for building. I've been asked by my boss to introduce react into the stack so we can toy around with converting some of the pages.
My goal is to not impact the existing implementation to heavily and instead output the result of webpack into a defined directory. This way I can just point the backend at that location for pathing.
So far I have an apps folder in my workspace that contains all my react stuff that works on its own. This was generated using 'npx create-react-app folderName'.
I've somewhat read up on how to set the export but am generally confused. As a lot of resources I've found assume a new setup or a replacement of an existing setup. While I'm looking to only replace a single page currently.
I don't think create-react-app is the right tool here, since you don't create a complete application with React but incrementally add React code. I would suggest using Webpack on its own. This makes your application cleaner and easier to maintain with your other code.
If you want to keep your React code separate from your existing code you can create a library based on webpack's Authoring Libraries Guide. You can than render your components with ReactDOM.render() (Docs). Note that you can call this function (almost) unlimited times on one page which allows you to partially replace your existing code.
Replacing a page then means to create a root DOM element and call the render function:
<!-- page.html -->
<html>
<head></head>
<body>
<!-- more html -->
<div id="page-root" />
<!-- more html -->
</body>
</html>
import React from 'react'
import ReactDOM from 'react-dom'
import Page from './routes/YourPageComponent'
ReactDOM.render(<Page />, document.getElementById('page-root'));
The previous code means that you render your code in the new code which is transpiled by your webpack loaders (e.g. Babel-Loader, Typescript-Loader). If you want to render the code in the existing code, look at the Doc's about Webpack Libraries to export render functions into a global context. The following scripts are an example out of my head.
// components/PageExampleComponent.jsx
import React from 'react';
export default function({pageTitle="example"}){
return <div>
<h1>{pageTitle}</h1>
</div>
}
// libary/index.js
import PageExampleComponent from './components/PageExampleComponent';
export const MyLibrary = {
PageExampleComponent
}
The previous code requires the following (partial) Webpack config to export MyLibrary:
module.exports = {
//...
output: {
library: 'MyLibrary',
// based on a fast look into the docs, I think the following are optional:
libraryTarget: 'window',
libraryExport: 'default'
}
};
To render a component of this library, you need React and ReactDOM as scripts in your website - and of course your own library script. You can than call ReactDOM.render() in plain JavaScript:
ReactDOM.render(
React.createElement(window.MyLibrary.PageExampleComponent),
document.getElementById('page-root')
Another idea would be to move everything into Webpack. This might be easier, as you don't have barriers of different Javascript-Versions and dialects (e.g. with and without JSX support). You can even separate your jQuery code and your React code by using two entry points:
module.exports = {
//...
entry: {
oldCode: './src/jqueryIndex.js',
replacement: './src/reactIndex.js'
},
output: {
filename: "[name].js"
}
};

Add PolyFill.js in AngularJS application

WE are embedding PowerBi JavaScript SDK in angularJs App. PowerBI Javascript SDK makes use of the Promise.
IE 11 do not support Promises. Lot of posts directed me to make use of ployfill.js for the same.
My Question is how do I Inject PolyFill.js file in angularjs app?
If you are using Webpack for bundling, add the polyfill.js before your main entry script.
module.exports = {
entry: ['polyfill.js', './main.js']
};
If you are using script tags in html, make sure to include the script before any other library that uses promises (PowerBI):
<script src="path/to/polyfill.js"></script>
A more modular approach is to use core-js and include only the polyfill you need:
module.exports = {
entry: ['core-js/fn/promise', './main.js']
};

Build once and deploy build file in multiple environments with minimal changes React and Webpack

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]);

Stripe with React JS

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(

Resources