I am very much new to React. The following is my first script.
But I am getting the following error.
Uncaught SyntaxError: Unexpected token <
I have even searched through google/SO. But I couldn't get it to work.
<!DOCTYPE html>
<html>
<head>
<title>First React App</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>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const name = 'John doe'
const handle = '#john_doe'
function NameComponent (props){
return <h1>{props.name}</h1>;//The problem is here using JSX syntax
}
function HandleComponent(props){
return <h3>{props.handle}</h3>;
}
function App(){
return (
<div id="container">
<NameComponent name={name}/>
<HandleComponent handle={handle}/>
</div>
);
}
ReactDOM.render(<App />,document.getElementById('app'));
</script>
</body>
</html>
To make your code work as it is currently, you just need to add type="text/babel" to the script tag that contains the code that you intend to transpile using babel.
From the babel docs:
When loaded in a browser, #babel/standalone will automatically compile and execute all script tags with type text/babel or text/jsx
Working code with just this change
<html>
<head>
<title>First React App</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>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script type="text/babel">
const name = 'John doe'
const handle = '#john_doe'
function NameComponent (props){
return <h1>{props.name}</h1>;//The problem is here using JSX syntax
}
function HandleComponent(props){
return <h3>{props.handle}</h3>;
}
function App(){
return (
<div id="container">
<NameComponent name={name}/>
<HandleComponent handle={handle}/>
</div>
);
}
ReactDOM.render(<App />,document.getElementById('app'));
</script>
</body>
</html>
Though this works, using create-react-app or codesandbox is generally much simpler for beginners.
In order to have a bare minimum setup with react (with no compilation step), you need either to use React.createElement syntax instead of JSX tags (check https://reactjs.org/docs/add-react-to-a-website.html), or use something like htm
Personally I would just use Create React App to help with the initial setup. This will configure babel (among a lot of other things) for you and do the proper JSX transpilation. Although in the future it will be good for you to know exactly whats under the hood of create-react-app and maybe make your own setup.
Simply install babel using npm with this command:
npm install --save #babel/standalone
Also include this line in your HTML file:
<script type="text/babel" src="like_button.js"></script>
Example code:
<script src="https://unpkg.com/react#17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script type="text/babel" src="like_button.js"></script>
if you have script tag in your index.html give it a type="text/babel"
If that didn't fix it try:
Removing the homepage line entirely from the package.json in the react app directory fixed it somehow.
Related
I am currently working on a react application and everything was working fine until recently when I noticed that all the external scripts I defined in the public/html no longer works when rendering pages using react-router-dom, but works fine when I call the pages directly.
These is my html file body tag:
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/plugins.bundle.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/scripts.bundle.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/intro.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/widgets.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/chat.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/modals/create-app.js"
></script>
</body>
Everthing works perfectly if I render the page this way:
const App = () => {
return (
<UserDashboard/>
);
};
export default App;
But when using react-router-dom, it doesnt throw any errors but nothing works
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<UserDashboard />/>
<Route path="/login" element={<Login />} />
</Routes>
</BrowserRouter>
);
My folder structure
Please does anyone know why this is happening and how can I fix it, cause I'm using a template and those scripts are necessary for the template to function properly.
I'm beginning to think this has to with react-router-dom version 6, cause I have not encountered this problem when working on previous projects. Its the only thing I can suspect would downgrading the react-router-dom be a bad idea?
I had a similar issue where I needed to load scripts in html tags in an app created from create-react-app library and found that I needed to put them in the body, afer rootand use the deferkeyword as below:
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/CCapture.js'></script>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/gif.js'></script>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/webm-writer-0.3.0.js'></script>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/download.js'></script>
Can't remember if using the %PUBLIC_URL% variable was part of the solution or I just used it because the template had similar.
The script paths are relative to the current URL path. They probably work without issue if/when the app loads and you are on the root "/" route, but have issue when on any sub-route.
Specify absolute paths in your public directory instead.
<script src="/assets/js/plugins.bundle.js"></script>
<script src="/assets/js/scripts.bundle.js"></script>
<script src="/assets/js/intro.js"></script>
<script src="/assets/js/widgets.js"></script>
<script src="/assets/js/chat.js"></script>
<script src="/assets/js/modals/create-app.js"></script>
I had a similar issue. I'm using Electron with webpack and was able to resolve this by adding a custom file protocol to handle custom requests for static files. Added within the window creation handler. This may be of help.
import { app, BrowserWindow, session } from 'electron';
//...
session.defaultSession.protocol.registerFileProtocol('asset', (request, callback) => {
const fileUrl = request.url.replace('asset://', '');
const filePath = path.join(app.getAppPath(), '.webpack/assets', fileUrl);
callback(filePath);
});
I have problems, importing a module to my index.js file. When I start debugging, I always get the error "Uncaught SyntaxError: Unexpected identifier"
My index.html file:
.
.
.
</body>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/defines.js"></script>
<script type="text/javascript" src="js/jgestures.js"></script>
<script type="text/javascript" src="js/mdb.js"></script>
<script type="module" src="index.js"></script>
<script type="module" src="js/global.js"></script>
</html>
The module I want to import "modals.js":
class Modals{
let b = 0;
}
export {Modals};
First line of my index.js file (where the error occures):
import {Modals} from './modals.js'
Does anyone has an idea what's wrong with my code?
Looks like you are not using ES6 classes properly. Also, keep in mind not all browsers work with ES6, it might be better to use functions or a transpiler like Babel.
I'd recommend reviewing the docs to get a refresher, but here is a code snippet of what you'd need to do for your example to work with ES6 classes
Your modals.js file would become:
class Modals{
constructor (b) {
this.b = b;
}
}
export {Modals};
Your index.js:
import {Modals} from './modals.js';
let m = new Modals('something')
console.log('m', m)
Your index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script type="module" src="index.js"></script>
</body>
</html>
Good luck!
I would suggest first to check the browser support. ES6 modules have been around for a while now but it may be the case that your browser version does not support this syntax.
Then, you would need a transpiler like Babel to use this type of statements.
I have a html file, .js file and .jsx file. I have added/imported both .js and .jsx files in html file.
.js file has a function to return a div tag.
I would like to render the value returned by this function to root div tag in html.
I am thinking of invoking JS function within JSX and render the value returned by this JS function using ReactDOM.render.
Is it possible to invoke a JS function from .jsx file?
index.html has below content
<!DOCTYPE html>
<html>
<head>`enter code here`
<meta charset="UTF-8" />
<title>Hello World</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>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
<script type="text/babel" src="test.jsx"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
test.js has below content
function alertme() {
return "<div><h1>Hello, world!</h1></div>"
}
test.jsx has below content
function tick() {
const element = (
<div>{alertme()}</div>
);
ReactDOM.render(
element,
document.getElementById('root')
);
}
tick();
Instead of displaying hello world it is displaying complete html tag
What could be done fix this?
Yes you can access the function of .js file in the .jsx file.
You just have to import the .js file the file where you want to use the method.
For example:
import { connect } from 'react-redux';
And now in your jsx file you can use the connect method with required parameters.
Above import is just for example.
Hope it helps
You can use dangerouslySetInnerHTML function provided by react to turn a string in to an React element.https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.
function alertme() {
return "<div><h1>Hello, world!</h1></div>"
}
function tick() {
const element = <div dangerouslySetInnerHTML={{__html: alertme()}}></div>;
ReactDOM.render(
element,
document.getElementById('root')
);
}
tick();
<!DOCTYPE html>
<html>
<head>
<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="root"></div>
</body>
</html>
The following Simple ReactJS code is not working. Newbie needs help please!
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ReactJS Test</title>
<script crossorigin src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
</head>
<body>
<div id="container"></div>
<script type="text/babel">
var currentLocation = window.location;
ReactDOM.render(
<div>
<p>currentLocation : {currentLocation}</p>
</div>,
document.getElementById('container')
);
</script>
</body>
</html>
And Chrome console shows helpless error messages like this:
react-dom.production.min.js:67 Uncaught Error: Minified React error #31; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=31&args[]=http%3A%2F%2Fxxxxxxx.com%3A8080%2F_test%2Fsitetest_new.jsp&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
at m (react-dom.production.min.js:67)
at qb (react-dom.production.min.js:82)
at z (react-dom.production.min.js:87)
at C (react-dom.production.min.js:89)
at react-dom.production.min.js:94
at g (react-dom.production.min.js:43)
at f (react-dom.production.min.js:43)
at beginWork (react-dom.production.min.js:48)
at e (react-dom.production.min.js:18)
at k (react-dom.production.min.js:19)
Thanks in advance!
window.location returns an object. You can't embed a standalone object in JSX. You can only embed JavaScript expressions.
Try using JSON.stringify() to convert your object to a string.
You can run the snippet below or check out this CodePen Demo.
var currentLocation = window.location;
ReactDOM.render(
<div>
<p>currentLocation : {JSON.stringify(currentLocation)}</p>
</div>,
document.getElementById('container')
);
<div id="container"></div>
<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>
Note: If you just want a string value from your window.location object (e.g. href), you don't need JSON.stringify().
You could simply use window.location.href directly in your JSX (or set var currentLocation = window.location.ref;) - example.
I'm trying to get React.js to work client side on my LAMP stack web application. I want to implement the following slider on my website: https://github.com/airbnb/rheostat. I have managed to get react.js to work using the following guide: https://gist.github.com/jineshshah36/4a0326abb191781184e9.
The following code works:
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script type="text/babel">
var HelloComponent = React.createClass({
render: function() {
return (
<h1>Hello, World!</h1>
)
}
})
ReactDOM.render(<HelloComponent />, document.querySelector('#app'))
</script>
I tried to use the rheostat slider by changing the above to the following.
<div id="slider-root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://raw.githubusercontent.com/airbnb/rheostat/master/src/Slider.jsx"></script>
<link href="https://raw.githubusercontent.com/airbnb/rheostat/master/css/slider.css" rel="stylesheet" type="text/css">
<script type="text/babel">
import Rheostat from 'rheostat';
ReactDOM.render(<Rheostat />, document.getElementById('slider-root'));
</script>
Am I importing the files wrong? Do I need to process the jsx file before it can be executed by the browser? If yes, how do I do that?
Do I need to process the jsx file before it can be executed by the browser?
Yes, precisely. jsx is essentially a syntax extension primarily for working with React, and you will need to compile/transpile first. If you don't want to do that, you can simply leave jsx out altogether and just use:
ReactDOM.render(React.createElement(Rheostat), document.getElementById('slider-root'));
If you are interested in jsx, consider the following:
<div>
<span>Text here</span>
</div>
This is not valid JavaScript, the browser will barf up all sorts of syntax errors restlessly. This code first has to be compiled, or transpiled into valid JavaScript. When using React, the above is to be compiled into:
React.createElement(
"div",
null,
React.createElement(
"span",
null,
"Text here"
)
);
One of the most common tools for this is Babel. TypeScript also has built-in support for typed jsx, dubbed tsx.