Simple ReactJS code not working - javascript

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.

Related

Uncaught SyntaxError: Unexpected token < with React

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.

How can i access/invoke javascript function in JSX file?

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>

Spring Boot (inject script in reactjs)

I'm having a really difficult time figuring out what I possibly could do wrong as probably most scenarios has been tested.
I'm writing web app using Spring Boot and ReactJS for frontend. I'm trying for now to write simple script showing some plain text which is imported from separate file to html one. After doing so, I ended up with nothing really showing up.
Here is my structure of project:
and here is my app.js in which I have my component defined:
var CommentBox = React.createClass({
render: function() {
return (
<div className="commentBox">
Hello, world! I am a CommentBox.
</div>
);
}
});
ReactDOM.render(<CommentBox />, document.getElementById('content')
);
Below is the cardists.html page:
<!DOCTYPE html>
<html>
<head>
<title>Cardists</title>
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/
3.3.7/css/bootstrap.min.css"/>
</head>
<body>
<div id='root'></div>
<script src="react-15.0.1.js"></script>
<script src="react-dom-15.0.1.js"></script>
<script src="cdnjs.cloudflare.com/ajax/libs/babel-
core/5.8.23/browser.min.js"></script>
<script type="text/babel" src="../public/js/app.js"></script>
</body>
</html>
[PROBLEM]
Where could I possibly made a mistake as everything for first glance seems ok to me, but I'm getting blank page ;/
You are rendering your application in content div like
ReactDOM.render(<CommentBox />, document.getElementById('content')
But in you html file there is no div with content id. There is one div with id root so you need to render your component in that div like
ReactDOM.render(<CommentBox />, document.getElementById('root')

Babel CDN link not working

Here is my code:
index.html
<!DOCTYPE html>
<html>
<body>
<div id="story-app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.min.js"></script>
<!-- Load Babel -->
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script type="text/babel" src="components.js"></script>
</body>
</html>
My JS source resides in a file called components.js as below
class StoryBox extends React.Component {
render() {
return ( <div>Story Box</div> );
}
}
ReactDOM.render(
<StoryBox />, document.getElementById('story-app')
);
The code is really simple and I am looking to only add a DIV to the main page but I am getting the following error in the console
babel.min.js:5 Uncaught SyntaxError: Invalid regular expression: /[ªµºÀ-ÖØ-öø-ˈ-Ë‘Ë -ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ÒÒŠ-Ô¯Ô±-Õ–Õ™Õ¡-Ö‡×-תװ-ײؠ-يٮٯٱ-Û“Û•Û¥Û¦Û®Û¯Ûº-Û¼Û¿ÜÜ’-ܯÝ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢴࢶ-ࢽऄ-हऽà¥à¥˜-ॡॱ-ঀঅ-ঌà¦à¦à¦“-নপ-রলশ-হঽৎড়à§à§Ÿ-ৡৰৱਅ-ਊà¨à¨à¨“-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-àªàª-ઑઓ-નપ-રલળવ-હઽà«à« à«¡à«¹à¬…-ଌà¬à¬à¬“-ନପ-ରଲଳଵ-ହଽଡ଼à­à­Ÿ-ୡୱஃஅ-ஊஎ-à®à®’-கஙசஜஞடணதந-பம-ஹà¯à°…-ఌఎ-à°à°’-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-à²à²’-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-à´à´’-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-à·†à¸-ะาำเ-
Am I using the wrong link to babel.min.js? I got it from https://babeljs.io/docs/setup/#installation from Section 3 Usage
Downloaded the js file from here and it worked https://github.com/babel/babel-standalone/releases

Support for script type="text/babel" in Visual Studio Code

When I'm editing the below example HTML page in Visual Studio Code (borrowed from Facebook's React tutorial and slightly edited), if I write any Javascript code in the script block, it is not syntax highlighted. But if I change the script block type to "text/javascript" then the syntax highlighting works. But then any React-y/JSX code doesn't work as it is wired to work through Babel.
Is there any way to have the script tag "type" attribute set to "text/babel" and at the same time have proper syntax highlighting in Visual Studio Code?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React Tutorial</title>
<script src="https://npmcdn.com/react#15.3.0/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom#15.3.0/dist/react-dom.js"></script>
<script src="https://npmcdn.com/babel-core#5.8.38/browser.min.js"></script>
<script src="https://npmcdn.com/jquery#3.1.0/dist/jquery.min.js"></script>
<script src="https://npmcdn.com/remarkable#1.6.2/dist/remarkable.min.js"></script>
</head>
<body>
<div id="content"></div>
<script type="text/babel">
ReactDOM.render(
<div>Hello world!</div>,
document.getElementById('content')
);
</script>
</body>
</html>
I found a solution to this now.
Open up: (VS code home dir)\resources\app\extensions\html\syntaxes\html.json, and edit the regex for the script tag. That fixed the issue for me.
Well this is a workaround, probably will be better to change this in a post build process, but I found an easy way to do it with this new feature TagHelpers which will help to replace the javascript value by babel
So add a file TagHelpers/ScriptTagHelper.cs
[HtmlTargetElement("script", Attributes = "to_babel")]
public class ScriptTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.Attributes.SetAttribute("type", "text/babel");
}
}
In your page Index.cshtml
<script type="text/javascript" to_babel>
And dont forget to import TagHelpers in _ViewImports.cshtml or in your Index.cshtml
#using app1
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper *, app1
And voila! this render as babel.

Categories

Resources