Hey great folks of Stack Overflow. I am learning REACTJS right now. And it's throwing this error: Uncaught SyntaxError: embedded: Unexpected token var Comment = React.createClass({...});
Here's my code: `
<body>
<div id="example">
</div>
<div id="container">
</div>
<script type="text/babel">
var Comment = React.createClass({...});
var Board = React.createClass({
getinitialState: function(){
return{
comments: [
"I like bacon.",
"Want to get ice cream?",
"Okay, we've got enough comments now."
]
}
},
render: function() {
return(
<div className="board">
{
this.state.comments.map(function(text, i){
return(<Comment key={i}>{text}</Comment>);
})
}
</div>
);
}
})
ReactDOM.render(<Board/>, document.getElementById("container"));
</script>
<script src="https://npmcdn.com/react#15.3.0/dist/react.min.js"></script>
<script src="https://npmcdn.com/react-dom#15.3.0/dist/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script> <!-- older transpiler 5.8.24 works with this app-->
</body>
`
I am not sure what's going on here. I'm trying to create a component via var Comment which should have an array which is "var Comment = React.createClass({..}); I don't know why it's not recognizing it as an array that would be used. I would definitely appreciate some help on this, good folks of StackOverflow.
You are writing your React code in JSX which is not understood by the script tag. In order to run the React code either use the webpack or browserify to bundle your jsx into a .js file and then include that .js file in the script tag or in order to test your code use the JSFIDDLE to write your code . It has integration for JSX.
Sample webpack.config.js
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'src');
var APP_DIR = path.resolve(__dirname, 'src');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
}
};
module.exports = config;
index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
var Board = React.createClass({
getinitialState: function(){
return{
comments: [
"I like bacon.",
"Want to get ice cream?",
"Okay, we've got enough comments now."
]
}
},
render: function() {
return(
<div className="board">
{
this.state.comments.map(function(text, i){
return(<Comment key={i}>{text}</Comment>);
})
}
</div>
);
}
})
ReactDOM.render(<Board/>, document.getElementById("container"));
index.html
<body>
<div id="example">
</div>
<div id="container">
</div>
<script src="./src/bundle.js"></script>
</body>
You also need to have a package.json to provide all the dependencies.
Here is a good video tutorial series that can help you with all the configuration
JSX syntax is not understood by the script tag. The JSX needs to be compiled to JavaScript. Try out your example in JSFiddle. JSFiddle has integration scripts to work with React.
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js">
</script>
You can try moving your JSX code to a new .jsx file and referencing that file in your .html
I met the same problem with you, seems we were watching the same tutorial video :)
Anyway, getinitialState should be getInitialState. Watch out the 4th letter.
Do the one change in your snippet codes which it is given in above section.
Correct minor spelling mistake here.
getinitialState() should be getInitialState().
ES5 use getInitialState() to initialize the state variables i.e React.createClass(..).
ES6 use constructor() to initialized the state variables i.e class Comment extends React.Component(..)
Here is another example of ES6, please check out this.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<div id="content"></div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js'></script>
<script type="text/babel">
class CommentBox extends React.Component{
constructor(props){
super(props);
this.state = {
editable : false,
commentMsg : ">>"
};
}
save(event){
this.setState({commentMsg:event.target.value})
}
remove(){
this.setState({
editable:false
})
}
edit(){
this.setState({
editable:true
})
}
renderForm(){
return (
<div className="row">
<div>{this.props.children}</div>
<div><textArea name="commentBox" onChange={this.save.bind(this)}></textArea></div>
<button type="button" className="btn btn-danger">Save</button>
<button type="button" className="btn btn-success" onClick={this.remove.bind(this)}>Remove</button>
{this.state.commentMsg}
</div>
);
}
renderHtml(){
return (
<div className="row">
<div>{this.props.children}</div>
<div>{this.state.commentMsg}</div>
<button type="button" className="btn btn-danger" onClick={this.edit.bind(this)}>Edit</button>
<button type="button" className="btn btn-success" onClick={this.remove.bind(this)}>Remove</button>
</div>
);
}
render() {
if(this.state.editable){
return this.renderForm(this);
}else{
return this.renderHtml(this);
}
}
}
class Board extends React.Component{
constructor(props){
super(props);
this.state ={
comments:[
'Techical Comments',
'Wordpress Comments',
'Facebook Comments'
]
}
}
render(){
return(
<div className="container-fluid">{
this.state.comments.map(function(text,i){
return (
<CommentBox key={i}>{text}</CommentBox>
);
})
}
</div>
);
}
}
ReactDOM.render(
<Board />
, document.getElementById('content'))
</script>
</body>
</html>
Related
I'm beginner in ReactJS and am trying to run the following code:
#{
ViewBag.Title = "Index";
}
<h2>Hello World-React JS</h2>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script type="text/javascript">
var HelloWorldComponent = React.createClass({
getInitialState: function () {
return {
serverMessage: ''
};
},
componentDidMount: function () {
$.get('/Home/getmessage', function (result) {
if (this.isMounted) {
this.setState({
serverMessage: result
});
}
}.bind(this));
},
render: function () {
return ("<h1>{this.state.serverMessage}</h1>");
}
});
ReactDOM.render(<HelloWorldComponent />, document.getElementById("helloworldcontainer"));
</script>
<div id="helloworldcontainer"></div>
As you can see this is VS2017 MVC simple test application.
Actually, in VS editor I have some complaints that is shown on the screen shot bellow:
How to fix it and run it?
Change your script type as <script type="text/babel">
sample code :
<html>
<head>
<title>demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
</head>
<body>
<div id="container"/></div>
<script type="text/babel">
class MessageBox extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<div className={`messageBox ${this.props.type} || hidden`}>
{this.props.message}
</div>
</div>
);
}
}
class NameInput extends React.Component {
constructor(props) {
super(props);
this.state = {
message: {
type: "success",
body: "Now my message is in NameInput's state"
}
}
this.buttonClicked = this.buttonClicked.bind(this);
}
buttonClicked(evt) {
alert("hi");
}
render() {
let msg = this.state.message;
return (
<div>
<label>Name: <input type="text" /></label>
<button onClick={this.buttonClicked}>Click me!</button>
<MessageBox type={msg.type} message={msg.body}/>
</div>
)
}
}
ReactDOM.render(
<NameInput />,
document.getElementById('container')
);
</script>
</body>
</html>
Hope this helps.
as #Adeel Imran suggests, For just checking how react works, this is fine. For future development use babel-cli and try to write a component in a separate file.
see I am new in react.js and include react and react dom ...but here, I am including cdn but the error will come with the console.kindly help me.
<html>
<head>
<script src="https://unpkg.com/react#0.14.7/dist/react.js">
</script>
<script src="https://unpkg.com/react-dom#0.14.7/dist/react-
dom.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
core/5.8.23/browser.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
let HocCompont= (BasicComponent) => class extends
react.Component {
render(){
return(
<div className="abc"> <BasicComponent/> </div>
)
}
}
const StatelessCoponent = () =>{
return( <button>I am button</button>
)
}
let ExtendedButton = HocCompont(StatelessCoponent);
ReactDOM.render(<ExtendedButton/>,document.getElementById("app"));
</script>
</body>
</html>
I have three files, percentGuageWidget.js, index.html, and main.js
percentGuageWidget.js has some react.js & jsx code
I am getting renderWidget is not defined. It seems if I call renderWidget in the percentGuageWidget.js, it works fine, but it won't work when called elsewhere.
How do I make it so I can call it from outside of that file.
class PercentGuageWidget extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 0
}
}
componentDidMount() {
var widget = this;
setInterval(function(){
widget.setState({value:Math.round(Math.random()*100)});
}, 1000)
}
/* The render will be updated whenever state changes are made to the widget */
render() {
return (
<div className="percent-guage-widget widget">
<div className="bar" style={{width:this.state.value + "%"}}></div>
<div className="amount">{this.state.value}%</div>
</div>
);
}
}
var container = document.getElementById('target-widget-container');
function renderWidget(){
ReactDOM.render(<PercentGuageWidget />, container);
}
<html>
<head>
<script> var appGlobals = {} </script>
<script
src="http://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
crossorigin="anonymous"></script
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="target-widget-container"></div>
</body>
<script src="https://unpkg.com/react#15.0.1/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15.0.1/dist/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" src="widgets/percentGaugeWidget.js"></script>
<script>renderWidget();</script>
</html>
I am brand spanking new to this React stuff and stumbling around trying to understand all of the moving parts. I have started a server with the webpack dev server and attempting to render my code to http://localhost:8080/ but to no avail. It's just a simple form component. There are more than likely many things wrong with how I have things set up, but again, still learning! Thanks for any help anyone can offer. I have an index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Practicing Components</title>
</head>
<body>
<div id="app"></div>
<script type='text/babel'></script>
</body>
</html>
This index.html file is rendering my main.js file:
import React from 'react';
import ReactDOM from 'react-dom';
class Main extends React.Component {
render() {
return (
<div>
<h1>Welcome to the Name Board!</h1>
<Form />
<Button />
</div>
);
}
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state= {value: 'Please type your name.'};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
return (
<input type="text" value={this.state.value} onChange={this.handleChange} />
);
}
}
class Button extends React.Component {
render() {
return (
<button value="Submit">
</button>
);
}
}
ReactDOM.render(<Main />, document.getElementById('app'));
I've set up my module loaders and entry point and all that in my webpack.config.js:
var path = require("path");
module.exports = {
entry: {
app: ["./main.js"]
},
output: {
path: path.resolve(__dirname, "build"),
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['react', 'es2015']
}
}
]
}
};
However, despite not having any error messages and my server being successfully connected, I am rendering nothing.
Looks like you're not even loading the bundle:
<script src="/build/bundle.js"></script>
It's not React. It's the HTML code. It doesn't seem to be telling the browser to load the bundle from anywhere, e.g. the <script> tag doesn't have an attribute src="/build/bundle.js".
So maybe to fix it, you'd have better luck after changing your HTML code to look like so?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Practicing Components</title>
</head>
<body>
<div id="app"></div>
<!-- See how "src" is now set to "app.bundle.js"? -->
<script src='/build/bundle.js'></script>
</body>
</html>
I admit that I am a newbie in ReactJS but I am encountering a very weird issue. I am doing the first part of animations tutorial of react here https://facebook.github.io/react/docs/animation.html and I am always having a "Uncaught ReferenceError: require is not defined". Please help below is my whole code:
<html>
<head>
<meta charset="utf-8" />
<title>Django React Personal Project</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>
</head>
<body>
<div id="content"></div>
<script type="text/babel">
var ReactCSSTransitionGroup = require('react-addons-css-transition-group');
var TodoList = React.createClass({
getInitialState: function() {
return {items: ['hello', 'world', 'click', 'me']};
},
handleAdd: function() {
var newItems =
this.state.items.concat([prompt('Enter some text')]);
this.setState({items: newItems});
},
handleRemove: function(i) {
var newItems = this.state.items;
newItems.splice(i, 1);
this.setState({items: newItems});
},
render: function() {
var items = this.state.items.map(function(item, i) {
return (
<div key={item} onClick={this.handleRemove.bind(this, i)}>
{item}
</div>
);
}.bind(this));
return (
<div>
<button onClick={this.handleAdd}>Add Item</button>
<ReactCSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300}>
{items}
</ReactCSSTransitionGroup>
</div>
);
}
});
ReactDOM.render(
<TodoList />,
document.getElementById('content')
);
</script>
</body>
</html>
Use the react-with-addons bundle if you want to use the addons via <script> tags.
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;