React JS Uncaught ReferenceError : require is not defined - javascript

I'm currently trying to get React to work by CDN.
When I run the index.html file manually it works. But when I put my files onto a web server like XAMPP, I get hit with
Uncaught ReferenceError : require is not defined
index.html:
<html>
<head>
<title>TestApp</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script src="./node_modules/moment/moment.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel" src="./react.js"></script>
</body>
</html>
react.js:
const Aest = ({test}) => {
return (
<div>WATss {test}</div>
)
}
class Test extends React.Component{
constructor(){
super()
this.state={
test: 0
}
}
inc(){
this.setState({
test: ++this.state.test
})
}
render(){
return(
<React.Fragment>
<div>test: {this.state.test}</div>
<button onClick={()=>this.inc()}>Add</button>
<Aest test={this.state.test}/>
</React.Fragment>
)
}
}
ReactDOM.render(<Test />,document.getElementById('app'));

require is not understood by default in some web severs, to allow it to be recognized first. use require js. npm install it. and import it.

Related

Adding React to HTML (without create-react-app installation)

I'm trying to follow this official React Documentation on how to add React to a website.
In file main.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<div id="root"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react#18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#18/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
<script src = "states_clock.js"> </script>
</body>
</html>
In file states_clock.js
// states_clock.js
'use strict';
const domContainer = document.getElementById('root');
const root = ReactDOM.createRoot(domContainer);
class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
function tick() {
root.render(<Clock date={new Date()} />);
}
setInterval(tick, 1000);
Both files are in the same folder.
When I open the html page in chrome, I get the error message:
Uncaught SyntaxError: Unexpected token '<' (at states_clock.js:11:7)
The < being complained about is that of the div in the js file.
This:
class Clock extends React.Component {
render() {
return (
<div>
is not JavaScript syntax - it's JSX syntax.
When you do
<script src = "states_clock.js"> </script>
as you would with any normal script tag, you're telling the browser to interpret and run it as a standard JavaScript file, which doesn't work, because it isn't. Add the attribute type="text/babel" to the script tag so it doesn't get run as JavaScript, and so that Babel Standalone sees that it's a script tag for it to process.
<script src="states_clock.js" type="text/babel"></script>
You could also write the JSX inline, like this:
<script crossorigin src="https://unpkg.com/react#18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"></script>
<div id='root'></div>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script type="text/babel">
'use strict';
const domContainer = document.getElementById('root');
const root = ReactDOM.createRoot(domContainer);
class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
function tick() {
root.render(<Clock date={new Date()} />);
}
setInterval(tick, 1000);
</script>
So, thanks to the comment by ChrisG, I understood that we're not supposed to use JSX in this part of the tutorial.
In that spirit, here's my solution:
'use strict';
const e = React.createElement;
const domContainer = document.getElementById('root');
const root = ReactDOM.createRoot(domContainer);
class Clock extends React.Component {
render() {
return e('div', null, e("h1", null, "Hello, world!"),
e("h2", null, "It is ", this.props.date.toLocaleTimeString(), "."));
};
}
function tick() {
root.render(e(Clock, {date: new Date()}, null))
}
setInterval(tick, 1000);
P.S.: Here's useful link that transforms JSX code into non-JSX code.

Is there a way to import modules in React without create-react-app?

I've just started using react and was using the create-react-app from npm until today. I've gotten the react and reactdom code from
https://unpkg.com/react#15/dist/react.js
https://unpkg.com/react-dom#15/dist/react-dom.js
I've saved the files as:
/Test/react/react.js
/Test/react/react-dom.js
This is my index.js:
<!--/Test/index.js-->
<html>
<head>
<title>React Hello World</title>
</head>
<body>
<div id="root"></div>
<script src="react/react.js"></script>
<script src="react/react-dom.js"></script>
<script src="App.js"></script>
</body>
</html>
I have created a module called Greetings, given below:
//Test/Components/Greetings.js
class Greetings extends React.Component {
render() {
return React.createElement(
"h1",
null,
"Greetings, " + this.props.name + "!"
);
}
}
export default Greetings;
And I've created an App.js, given here:
//Test/App.js
import Greetings from "./Components/Greetings";
ReactDOM.render(
React.createElement(Greetings, { name: "Me" }),
document.getElementById("root")
);
I'm getting this error:
Uncaught SyntaxError: Unexpected identifier
Is there an easy way to import a react module?
import and export are Node.js keywords. On the client-side you don't need them. Simply include your javascript files in the html:
<script src="App.js"></script>
<script src="Greetings.js"></script>

React importing material-ui components not working

I'm new to React. I have a local development server (node http-server) and have installed material-ui package.
According to the material-ui docs, to add a component, I simply import it like any other module:
import Button from '#material-ui/core/Button';
However, when I try this, my webserver is returning a 404 and Firefox console outputs this: Loading module from “http://localhost:8080/node_modules/#material-ui/core/Button/” was blocked because of a disallowed MIME type (“text/html”)
The directory is accessible because I can reference the ./node_modules/#material-ui/core/Button/Button.js file and it is returned by http-server. But if I import that file, I get
SyntaxError: import not found: default.
I've tried importing index.js from that directory, but get same error.
How do I import the Button component (as shown in the material-ui example) correctly?
Here is my code (being served by http-server on localhost:8080)
(I am using npx babel to compile the JSX to js before serving)
test.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Test React</title>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
</head>
<body>
<div id="app"></div>
<!-- React scripts -->
<script type="module" src="./test.js"></script>
</body>
</html>
test.js:
import { Mod1 } from './module1.js';
export class TestComponent extends React.Component
{
render()
{
return <h1>Hello world!</h1>;
}
}
export const TestC2 = () =>
{
return <h2>This is a h2</h2>;
}
ReactDOM.render(<div><TestComponent /><TestC2 /><Mod1 /></div>, document.getElementById('app'));
module1.js
// module1
import Button from './node_modules/#material-ui/core/Button';
export class Mod1 extends React.Component
{
constructor(props)
{
super(props);
this.state = {};
}
componentWillMount(props)
{
console.log("willMount", props);
}
componentDidMount(pp, ps)
{
console.log("didMount", pp, ps);
}
render()
{
console.log('render', this.props, this.state);
return <Button />;
}
}

How to perform import/export in client-side React JSX using Babel-Standalone

I'm using Babel-Standalone to use JSX in a React application without using NPM. Babel apparently translates 'import' statements into 'require' statements; importing 'require.js' and other dependencies to make this work produces more errors.
Surely, there must be a simple way to perform an import/export in the context of client-side JSX. Please advise (no Node/NPM/Webpack solutions are sought here; CDN of appropriate library(ies) and rewrite of import statement, etc., are sought).
<!doctype html>
<html lang="en-us">
<head>
<title>React JSX Babel-Standalone Import/Export Problem</title>
<meta charset="utf-8">
</head>
<body>
<div id="root"></div>
<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/babel.min.js"></script>
<script type="text/babel">
// See MyExport.js text below this SCRIPT
// Goal: to employ <MyExport /> in the return of App.
// import MyExport from "./MyExport";
const App = () => {
return (
<div>Hello</div>
);
};
ReactDOM.render(<App />, document.querySelector("#root"));
</script>
<!-- MyExport.js:
const MyExport = () => {
return (
<div>MyExport</div>
);
};
export default MyExport;
-->
</body>
</html>
There is a solution: (1) The JSX script containing the export must be included in a SCRIPT element along with the others; it cannot simply be referenced by another script without. (2) Both that JSX script and the JSX script importing from it must have the custom attribute data-plugins="transform-es2015-modules-umd" along with the expected attribute type="text/babel". Run the following HTML, a modification of what was provided in the question, which provides the solution (you'll have to create MyExport.js locally to run it):
<!doctype html>
<html lang="en-us">
<head>
<title>React JSX Babel-Standalone Import/Export Problem</title>
<meta charset="utf-8">
</head>
<body>
<div id="root"></div>
<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/babel.min.js"></script>
<script data-plugins="transform-es2015-modules-umd" type="text/babel" src="./MyExport.js"></script>
<script data-plugins="transform-es2015-modules-umd" type="text/babel">
import MyExport from "./MyExport";
const App = () => {
return (
<MyExport/>
);
};
ReactDOM.render(<App />, document.querySelector("#root"));
</script>
<!-- MyExport.js:
const MyExport = () => {
return (
<div>MyExport element is imported!</div>
);
};
export default MyExport;
-->
</body>
</html>
I hope this helps someone else.
you should include first all needed component files, then run the app js file
Example:
<div id="root-react"></div>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js" crossorigin></script>
And the file's tree is something like:
js/app.js
js/subcomponent.js
The app.js content is for example:
"use strict";
class MainReact extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<strong>app.js</strong> is loaded<br/>
<SubComponent />
</div>
)
}
}
ReactDOM.render(<MainReact />, document.getElementById("root-react"));
subcomponent.js content:
"use strict";
class SubComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<span> SubComponent-is-working </span>
)
}
}
customElements.define('subcomponent', SubComponent);
The file inclusion in the html file should be:
<script type="text/babel" src="js/subcomponent.js"></script>
<script type="text/babel" src="js/app.js"></script>
Hope it helps somebody.
CodePen demo
Babel isn't a module bundler or a module system implementation, babel is just a transpiler to provide access to the latest JS features that aren't supported in the browser or node.
If you want to use ES Modules without any third parties like webpack, rollup, etc. have a look at https://developers.google.com/web/fundamentals/primers/modules.
You should be able to do something like:
<script type="module">
import MyExport from "./url/to/MyExport.mjs";
const App = () => {
return (
<div>Hello</div>
);
};
ReactDOM.render(<App />, document.querySelector("#root"));
</script>
JS Modules via script tags is only supported in the latest versions of major browsers: https://caniuse.com/#feat=es6-module
Also, you'll need to workaround the fact that babel-standalone needs your script tags to be text/babel EDIT: the workaround is using a data-type="module" tag as well as the type="text/babel" tag: https://babeljs.io/docs/en/babel-standalone#usage

Converting a dynamic HTML page to React/JSX

As a simple example, suppose I had these two files:
example.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8" />
<title>Button example</title>
<script type="text/javascript" src="ButtonHandler.js"></script>
</head>
<body id="body" onload="init()">
<button onclick=buttonHandler.writeToConsole()>Button</button>
<script>
function init() {
buttonHandler = new ButtonHandler();
}
</script>
</body>
</html>
ButtonHandler.js
function ButtonHandler() {
};
ButtonHandler.prototype.writeToConsole = function () {
console.log('Writing');
}
This simply prints to the console whenever the button is clicked.
Ignore that the ButtonHandler's constructor is empty, and that I could just easily call 'console.log' in the onclick directly. This is a simplified version of an issue I'm having, with several classes.
My question is, how would I go about translating this to React/JSX, ideally without modifying the Javascript files (in this case, just ButtonHandler.js). Ideally this means no exporting/importing, I'd like to do it how the HTML file does it - it just links to the script in the <\head>.
The closest I have is something like this:
convert.jsx
import * as React from 'react';
export default class Entry extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
buttonHandler = new ButtonHandler();
}
render() {
return (
<div>
<title>Button example</title>
<button onclick="buttonHandler.writeToConsole()">Button</button>
</div>
)
}
}
But I get the error that ButtonHandler is undefined. I followed this stackexchange answer and placed
<script type="text/javascript" src="[rest of path...]/ButtonHandler.js"></script>
in the public/index head, and I added the 'window.ButtonHandler' in componentDidMount(), but I still get the error that it's undefined.
Am I doing something wrong, and if not, what other approach can I take?
edit: When I put ButtonHandler.js in the public folder with index, and I console log the window, I see it appear as a function of window, like the stackexchange answer describes. This doesn't happen when I have it in another folder, though. Same error however.
edit 2: Seems the only solution is to put ButtonHandler.js in the public folder and then call it in the constructor like the selected answer says. Then add a
<button onClick={() => this.buttonHandler.writeToConsole()}>Button</button>
to call it.
In create react app, you should be able to add any js files to your public folder for use in your project. You just need to reference the files in your script like:
<script type="text/javascript" src="%PUBLIC_URL%/ButtonHandler.js"></script>
That will make sure that it looks in the public folder when building.
The only problem with that is that the files won't be minified in the bundle.
Edit
You will have to reference the global variable inside your component as well.
/* global ButtonHandler */
import * as React from 'react';
export default class Entry extends React.Component {
constructor(props) {
super(props);
this.buttonHandler = new ButtonHandler();
}
render() {
return (
<div>
<title>Button example</title>
<button onclick={this.buttonHandler.writeToConsole}>Button</button>
</div>
)
}
}
You'll want to import that ButtonHandler js code. If it's not something you've written yourself, the easiest thing to do would be to see if it already exists as a React package. If it's your own file, then you'll want to export the functions in ButtonHandler.js, import ButtonHandler in your React component, then you'll have access to them in the component.
ButtonHandler.js
export function writeToConsole() {
console.log('Writing');
}
convert.jsx
import React, { Component } from 'react';
import { writeToConsole } from './ButtonHandler';
export default class Entry extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<title>Button example</title>
<button onclick={this.writeToConsole}>Button</button>
</div>
)
}
}

Categories

Resources