Import user defined component with React CDN, - reactjs

I'm using react with their CDN scripts (as well as react-dom and babel-standalone) that I've saved out to some files due to security practices with network connectivity, and am trying to figure out code organization.
Disclaimer: I'm aware that I need webpack or something to compile to get access to require or normal imports. I'm wondering if there's a way to organize my components without having to add a script tag in my main html for every single file.
The error that I'm getting is Uncaught ReferenceError: require is not defined. The research that I've done is saying that I need to add each file used by my other javascript with a tag in the html. This is cumbersome especially if I have a large(ish) project. It's not scalable. How can I organize the various components that I have without having to have a massive head section with all of the wonderful script tags?
I've seen some hacks, but they're older and with the advent of new react versions and browser capabilities, so I thought I'd try and see what is being used out there to solve this problem now.
p.s. this is the first experience I have with React CDN, but I've written apps in RN before.
My code is:
<html>
<head>
<script src="react.js" />
<script src="react-dom.js" />
<script src="babel.js" />
<script type="text/jsx" src="app.js" />
</head>
<body>
<div id="root" />
</body>
</html>
app.js
import Greeting from './greeting';
const App = () => {
return (
<Greeting text='Hello World' />
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
greeting.js
const Greeting = ({ text }) => {
return (
<h1>{text}</h1>
);
}
export default Greeting;

You cannot use React or JSX in the browser without some sort of build step. React only distributes CJS, no ESM, so it needs build tooling. Babel is used to transpile, though I'm not entirely sure it makes sense to use in this context. It's a lot of overhead.
Take a look at https://blog.jim-nielsen.com/2020/react-without-build-tools/ if you want to go the no-build tools route.
You'll have to use alternative versions of React as well as alternative syntax to JSX.

Try this
NOTE: Only when you proper setup of webpack and babel. require is required of cjs modules.
if you have done your setup try following.
1. const module = require('modulename') only when module is exports as modules.export = modulename
2. Try adding this plugin babel-plugin-import in your babel config

Importing greatings.js in app.js won't work. Instead, you import all the javascript files that you are using in the HTML file only then it would work.
<script type="text/babel" src="greatings.js"></script>
in the HTML file.

Related

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"
}
};

ReactJS - Redirect with web browser

Just starting learning ReactJS. I'm trying to redirect using the Redirect component <Redirect to="/dashboard" />. However, ReactJS is not familiar with this component by default (getting Redirect is not defined on console log).
After some reading, I saw that the Redirect component needs to be imported (import React from 'react'). However, since it's a web project, I do not use a webpack but rather import the entire library with:
<script crossorigin src="https://unpkg.com/react/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
So my question(s) is how do I use Redirect for a web project, or rather how to import components for a web project for ReactJS.
Redirect component is not part of react. import React from 'react' is importing the react object which contains things like React.Component.
I'm assuming you mean Redirect from react-router in which case you should also add a script for react-router-dom and reference via ReactRouterDOM.Redirect.
P.S. If you're creating something you intend to release you're better off generating a project with create-react-app. Nobody uses scripts directly anymore and you are using development versions of babel and react which are slow and large.

React is not defined when bundling

I am new to TypeScript and thought I would tray the product List demo from ReactJS website with it. I have got so far, but currently getting
external "React":1 Uncaught ReferenceError: React is not defined
at Object.react (external "React":1)
at __webpack_require__ (bootstrap:19)
at Object../src/client/app/index.tsx (index.tsx:1)
at __webpack_require__ (bootstrap:19)
at bootstrap:83
at bootstrap:83
and I am not too sure why, if I include it as an external in my webpack.config.js it works fine, but I am wanting to bundle it with the rest of the src ready for intranet applications that dont have access to the big bad world.
Any help would be appreciated.
I am importing thus import * as React from 'react';
webpack throws no errors
INDEX.TSX
import * as React from 'react';
var ReactDOM = require('react-dom');
import FilterableProductTable from './components/FilterableProductTable';
import Basket from './components/Basket';
ReactDOM.render(
<div>
<FilterableProductTable />
<Basket />
</div>,
document.getElementById('app')
);
I've been having this issue too. After googling the error for a day or so, I stumbled across this page.
Following the link provided by octavioccl in the comments - (http://www.typescriptlang.org/docs/handbook/react-&-webpack.html).
I swear I've read this page a dozen or so times, and roughly tried following it while I've been converting my project across to TypeScript. Anyways, what helped me what this section here:
"We’ll also need a page to display our Hello component. Create a file at the root of proj named index.html with the following contents:"
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
</head>
<body>
<div id="example"></div>
<!-- Dependencies -->
<script src="./node_modules/react/umd/react.development.js"></script>
<script src="./node_modules/react-dom/umd/react-dom.development.js"></script>
<!-- Main -->
<script src="./dist/bundle.js"></script>
</body>
</html>
"Notice that we’re including files from within node_modules. React and React-DOM’s npm packages include standalone .js files that you can include in a web page, and we’re referencing them directly to get things moving faster. Feel free to copy these files to another directory, or alternatively, host them on a content delivery network (CDN). Facebook makes CDN-hosted versions of React available..."
I added the Dependancies to my index.html file and it sorted this issue.
Hopefully that helps someone else who stumbles across this.

Import external react component from CDN (React Bootstrap Slider)

I have a Django project and I want to use React on it. I have already created my own components and this works, but I dont know how to import third-party components from CDN.
To do this, I did:
Import React (develop or production version) in the base template:
<!-- baseTemplate.html -->
{# ReactJs#}
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
Also import the file where I create my components
<!-- baseTemplate.html -->
<script src="/one_directory/my_react.jsx" type="text/babel"></script>
and create the tag where it will be rendered.
<!-- template.html -->
<div id="container"></div>
And finally render my React components:
<!-- my_react.jsx -->
ReactDOM.render(
<App />,
document.getElementById('container')
);
This works correctly :)
Now, I want to import a third-party component (specifically, it's React Bootstrap Slider) from CDN, but I dont know how.
Maybe this is not possible, I dont know. How could I do it?
Thank you very much :]
I think you want a CDN from this npm package https://www.npmjs.com/package/react-bootstrap-slider (version 2.1.3)
There is a CDN at https://unpkg.com/react-bootstrap-slider
You can explore files for that at https://unpkg.com/react-bootstrap-slider/
However I could not get it to work as I get Component not found error.
In the github project https://github.com/brownieboy/react-bootstrap-slider it says
The control is implemented in UMD format, so should also work for
AMD/RequireJS, but I've not tested that. You can also add it as a
script tag.
If you want a CDN I you suggest to inform the owner to fix it or you can fork the project and generate a CDN-friendly file and host it yourself.

Why we need to use web-pack in ReactJs?

Why do we need to use webpack, is it only for bundling and inheriting Plugins to minimize and compress.
what are all the major roles webpack plays in web application development?
The uses of webpack include
Transpile the JSX syntax (HTML tags inside Javascript) into JS
Transpile the ES6 syntax (arrow functions, spead operator, etc) into browser supported versions of Javascript.
It is much better to split code into separate files (modules) which can be imported. Webpack 'bundles' all those files into a single JS file for production use
At the time of bundling, it can also perform optimisations like minify, uglify, etc.
BTW, you don't need to use webpack. For example,
<!DOCTYPE html>
<html lang="en">
<head>
<title>My First React Example</title>
</head>
<body>
<div id="greeting-div"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/cjs/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/cjs/react-dom-server.browser.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script type="text/babel">
var Greeting = React.createClass({
render: function() {
return (
<p>Hello, Universe</p>
)
}
});
ReactDOM.render(
<Greeting/>,
document.getElementById('greeting-div')
);
</script>
</body>
</html>
Here, the JSX code is getting 'transpiled' to JS on-the-fly. However, this is not very efficient in production use.
As you mentioned, Webpack is a bundling tool, and you can use any other bundling tools such as browserify / rollup.
React apps usually gonna use ES6 imports, and not all the browsers supports it yet, therefore you need in React apps use some bundler to solve those "imports" and create a bundle file that the current browsers understands.
Webpack just got more popular and robust in the Front End community therefore most of the "starter kits" like create-react-app will use it.

Resources