How to fix the beginner's ReactJS error? - reactjs

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.

Related

where does input to function come from

We have the following react html. In the callback function filterList() we have as a parameter 'input' filterList(input). Where does this object come from? Is this coming from the onClick event? what other objects are available?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Filtered List</title>
<script src="react/react.js"></script>
<script src="react/react-dom.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/jsx">
class FilteredList extends React.Component {
constructor(props) {
super(props);
var allItems = [ "anteater", "bear", "cat", "dog", "elephant", "fox" ];
this.state = { initialItems: allItems, currentItems: allItems };
}
filterList(input){
var updatedList = this.state.initialItems;
updatedList = updatedList.filter(function(item){
return item.search(input.target.value) !== -1;
});
this.setState({currentItems: updatedList});
}
render(){
console.log(this);
return (
<div className="filter-list">
<input type="text" placeholder="Filter" onChange={this.filterList.bind(this)}/>
<List items={this.state.currentItems}/>
</div>
);
}
};
class List extends React.Component {
render(){
return (
<ul> { this.props.items.map(function(item) {
return <li key={item}>{item}</li> }) }
</ul>
)
}
};
ReactDOM.render(<FilteredList/>, document.getElementById('container'));
</script>
</body>
</html>
Input has an onChange listener when something happens it gives parameter to the function of the onChange.
Without this parameter the onChange parameter can't know what changed :)
Few words: yes it comes from onChange
More on here https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onchange

Uncaught TypeError: React.createClass is not a function exception

I did a html page like this
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React project</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-core#5.8.38/browser.min.js"></script>
</head>
<body>
<div id="root"></div>
<script src="react.js" type="text/babel"></script>
</body>
</html>
And the file react.js like this
var Comp1 = React.createClass({
render: function() {
return(
<h1> Comp1 </h1>
);
}
});
ReactDOM.render(
<div>
<Comp1/>
</div>,
document.getElementById("root")
);
But, I got "Uncaught TypeError: React.createClass is not a function" exception, why?
Normally you would define a React component as a plain JavaScript class:
class Comp1 extends React.Component {
render() {
return <h1> Comp1 </h1>;
}
}
If you don’t use ES6 yet, you may use the create-react-class module instead:
var createReactClass = require('create-react-class');
var Comp1= createReactClass({
render: function() {
return <h1> Comp1 </h1>;
}
});
Or,
import React from 'react';
const Contacts = React.createClass({
render() {
return (
<div></div>
);
}
});
export default Contacts;

Calling a function in a file with jsx code in a js file

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>

Uncaught SyntaxError: embedded: Unexpected token var Comment = React.createClass({...});

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>

Reactjs require not defined

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;

Resources