Uncaught SyntaxError: Unexpected token < in React - javascript

I'm working on a react project and trying to display a dialog with react-bootstrap. I just copied a working react-bootstrap snippet in a js file but it's not working for me, I'm having Uncaught SyntaxError: Unexpected token < next to the <div className='static-modal'> line.
Here is the content of the js file:
(function (context) {
// notification view
TheGraph.Notification = React.createFactory( React.createClass({
//TheGraph.Notification = React.createClass({
componentDidMount: function () {
},
handleHide: function () {
alert('Close me!');
},
render: function () {
return (
<div className='static-modal'>
<Modal title='Modal title' bsStyle='primary' backdrop={false} animation={false} container={mountNode} onRequestHide={handleHide}>
<div className='modal-body'>
One fine body...
</div>
<div className='modal-footer'>
<Button>Close</Button>
<Button bsStyle='primary'>Save changes</Button>
</div>
</Modal>
</div>
);
}
});
})(this);
When I put use " in return line as follows:
return ("<div className='static-modal'><Modal title='Modal title' bsStyle='primary' backdrop={false} animation={false} container={mountNode} onRequestHide={handleHide}><div className='modal-body'>One fine body...</div><div className='modal-footer'><Button>Close</Button><Button bsStyle='primary'>Save changes</Button></div></Modal></div>");
I get this error:
Uncaught Error: Invariant Violation: ReactCompositeComponent.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object
Any idea what is the mistake here?

The code that you are using inside render is JSX , browsers as of now doesn't understand jsx . So we need transpilers to convert them to pure JavaScript .
You need to have a build process that transpiles your jsx code into javascript and then you should load that transpiled js in your HTML.
But if you just quickly want to play with react without setting up the build process , you can go here and do that manually every time and paste that inside render
React.createElement(
'div',
{ className: 'static-modal' },
React.createElement(
Modal,
{ title: 'Modal title', bsStyle: 'primary', backdrop: false, animation: false, container: mountNode, onRequestHide: handleHide },
React.createElement(
'div',
{ className: 'modal-body' },
'One fine body...'
),
React.createElement(
'div',
{ className: 'modal-footer' },
React.createElement(
Button,
null,
'Close'
),
React.createElement(
Button,
{ bsStyle: 'primary' },
'Save changes'
)
)
)
);

Related

Test Conditionally Rendered component in React Js

I'm new to testing and I'm writing test cases for a react app.
I've a table with atoms in it.
<Table.Cell style={{ cursor: "pointer" }}>
<Icons
data-test="nameDeleteTable"
name="trash"
onClick={() =>
ConfirmBox({
title: "Confirm Deleting?",
message:
"Are you sure you want to delete this entry permanently?",
onClick: () => props.handleDelete(cell.name),
})
}
/>
</Table.Cell>
ConfirmBox has the following code
function ConfirmBox(props) {
return (
<div data-test="confirmboxAtom">
{confirmAlert({
title: `${props.title}`,
message: `${props.message}`,
buttons: [
{
label: "YES",
onClick: props.onClick,
},
{
label: "NO",
},
],
})}
</div>
);
}
confirmAlert is from a library named react-confirm-alert
The current attempt to test the table button click, gets to the onClick of <Icons ... /> using the code
const wrapper = getWrapper(component, "nameDeleteTable");
console.log("Wrapper " , wrapper);
wrapper.props().onClick();
expect(wrapper.length).toBe(1);
While checking the coverage for this, I'm able to get the onClick function to be covered but not the onClick of the ConfirmBox and I have no clue how to make it work.
You have to invoke a onClick() on whatever this react-confirm-alert renders to (I mean the html element).

Wordpress Gutenberg InnerBlock.Content is not being saved or rendered

I am creating a custom block in Gutenberg via custom plugin. My custom block contains InnerBlocks. The edit function appears to be working correctly, as I can add the block to the page, and place new block elements inside the block as intended. The issue arrises when I reload the page. After I update the page and reload the editor, all of the InnerBlock elements are gone. They are not being saved, and not being rendered on the frontend either. Unless I'm crazy, my save function is not built correctly. Any help would be great. I am well versed in Wordpress and JS, but new to React and Gutenberg. Thanks for any help!
( function( blocks, element, editor ) {
const el = element.createElement;
const { registerBlockType } = blocks;
const InnerBlocks = editor.InnerBlocks;
registerBlockType( 'dab/nest', {
title: 'Disruptive Nest',
icon: 'layout',
category: 'disruptive-blocks',
keywords: [ 'base', 'build', 'custom' ],
edit: function( props ) {
return (
el( 'div', {className: props.className + ' dab-full'},
el( 'div', {className: 'dab-content'},
el( InnerBlocks )
)
)
);
},
save: function( props ) {
return (
el( 'div',
el( 'div',
el( InnerBlocks.Content, null )
)
)
);
},
});
})( window.wp.blocks,
window.wp.element,
window.wp.blockEditor
);
I found this in the Block Editor Handbook ([https://developer.wordpress.org/block-editor/developers/block-api/block-edit-save/#classname):
"This is automatically added in the save method, but not on edit" [on the topic of props.className]. That is why I didn't have the classes mirrored initially. Reading it again led me to realize that mirroring the classNames on the "save" function isn't what fixed it, but just having the {} in there after each of the parent el( 'div',, even if you don't specify anything, is what fixed the function.
So, it works like this, and the className is automatically added to the first el( 'div',:
save: function( props ) {
return (
el( 'div', {},
el( 'div', {},
el( InnerBlocks.Content )
)
)
);
},
Thanks, #niklas for helping me realize this.

How to display what is in a React JavaScript file, or rather a file to be interpreted by React

I hive tried several things and have see it work conceptionaly here How to call and form a React.js function from HTML All i get in my HTML generated from this file is
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="BonApp">
<meta name="keywords" content="HTML,CSS,JavaScript">
<!-- <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"> -->
<link href="index.css" type="text/css" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link href='https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900' rel='stylesheet' type='text/css'>
<script src="https://code.jquery.com/jquery-2.2.2.min.js" integrity="sha256-36cp2Co+/62rEAAYHLmRCPIych47CvdM+uTBJwSzWjI=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/jquery.slick/1.5.9/slick.css" />
<link rel="stylesheet" type="text/css" href="slick.css" />
<link rel="stylesheet" type="text/css" href="slick-theme.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react-with-addons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.1/react-dom.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery.slick/1.5.9/slick.min.js"></script>
<script src="https://scontent.xx.fbcdn.net/t39.3284-6/13591530_1796350410598576_924751100_n.js"></script>
<script src="https://scontent.xx.fbcdn.net/t39.3284-6/13591520_511026312439094_2118166596_n.js"></script>
<title>BonApp</title>
</head>
<body>
<div id="nav"></div>
<div id="Gallery"></div>
<div id="whatsnew"></div>
<div id="advertiseApp"></div>
<div id="events"></div>
<div id="footer"></div>
</body>
<script type="text/javascript">
$('.autoplay').slick({
slidesToShow: 2
, slidesToScroll: 1
, autoplay: true
, autoplaySpeed: 2000
, });
</script>
</html>
which is exactly what I have put into it, meaning it is not calling from the JavaScript file, (which is identical to the mentioned in the stack overflow message previously mentioned) I hope the answer falls within the range of: "I have the wrong version of Babel".
All help is appreciated!!!
EDIT: Here is a copy of the JS code just to be sure.
var NavBar = React.createClass({
render: function() {
return (
/* NavBar */
<div className="dark_bg_color">
<img src="logo.png" />
<div className="table_center">
<div>
<ul>
<li>daily specials</li>
<li>gift gallery</li>
<li>events</li>
<li><i className="fa fa-search" /> search</li>
</ul>
</div>
</div>
<div className="right_nav">
<div className="table_center">
<div>
<button type="button">Sign Up</button>
<button type="button">Log In</button>
<div className="vertical-line"> </div>
<button type="button">Cart</button>
</div>
</div>
</div>
</div>
);
}
});
ReactDOM.render(<NavBar />, document.getElementById('nav'));
var Gallery = React.createClass({
render: function() {
return (
/* Gallery */
<div >
<div align="middle">
<div id="head">
<img id="pic" align="middle" max-width="100%" src="title_pic.png" />
<div align="left" className="big">
<div>
<span>Dine with the Best</span>
<div className="words">
<span>BonApp connects you with limited-time, exclusive meals and events offered by the city’s best chefs.<br /><br /><br /><button type="button">JOIN BONAPP</button></span>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
});
ReactDOM.render(<Gallery />, document.getElementById("Gallery"));
var WhatsNew = React.createClass({
render: function() {
return (
<div className="dark_bg_color">
<h2 style={{marginBottom: 30}}>
<span>What's New</span>
</h2>
<div className="autoplay">
<img src="whatsnew0.png" />
<img src="whatsnew1.png" />
<img src="whatsnew0.png" />
</div>
</div>
);
}
});
ReactDOM.render(<WhatsNew />, document.getElementById("whatsnew"));
var BonEvents = React.createClass({
render: function() {
return (
/* Events */
<div id="events" className="dark_bg_color">
<div className="box">
<div className="box-text">
<div className="horizontal-line" />
<div><div className="horizontal-line" /><p>LES BON CADEAUX</p></div>
<div className="horizontal-line" />
</div>
</div>
<h2>
<span>Bon Events</span>
</h2>
<div>
</div>
</div>
);
}
});
ReactDOM.render(<BonEvents />, document.getElementById("events"));
var IOS = React.createClass({
render: function() {
/* IOS */
return (
<div >
<h2>
<span />
</h2>
</div>
);
}
});
ReactDOM.render(<IOS />, document.getElementById("advertiseApp"));
var Footer = React.createClass({
render: function() {
return (
/* Footer */
<div>
<div className="footer_center">
<div>
<ul>
<li>ABOUT</li>
<li>PRESS</li>
<li>CONTACT</li>
<li>SUPPORT</li>
<li>BONAPP FOR RESTAURANTEURS</li>
</ul>
</div>
</div>
<div className="legal_center">
<div>
<ul>
<li>Copyright © 2016 BonApp Dining Inc.</li>
<li>Privacy Policy</li>
<li>Legal</li>
</ul>
</div>
</div>
</div>
);
}
});
ReactDOM.render(<Footer />, document.getElementById("footer"));
EDIT 2:
React CLI Output:
"use strict";
var NavBar = React.createClass({
displayName: "NavBar",
render: function render() {
return(
/* NavBar */
React.createElement(
"div",
{ className: "dark_bg_color" },
React.createElement("img", { src: "logo.png" }),
React.createElement(
"div",
{ className: "table_center" },
React.createElement(
"div",
null,
React.createElement(
"ul",
null,
React.createElement(
"li",
null,
"daily specials"
),
React.createElement(
"li",
null,
"gift gallery"
),
React.createElement(
"li",
null,
"events"
),
React.createElement(
"li",
null,
React.createElement("i", { className: "fa fa-search" }),
" search"
)
)
)
),
React.createElement(
"div",
{ className: "right_nav" },
React.createElement(
"div",
{ className: "table_center" },
React.createElement(
"div",
null,
React.createElement(
"button",
{ type: "button" },
"Sign Up"
),
React.createElement(
"button",
{ type: "button" },
"Log In"
),
React.createElement(
"div",
{ className: "vertical-line" },
" "
),
React.createElement(
"button",
{ type: "button" },
"Cart"
)
)
)
)
)
);
}
});
ReactDOM.render(React.createElement(NavBar, null), document.getElementById('nav'));
var Gallery = React.createClass({
displayName: "Gallery",
render: function render() {
return(
/* Gallery */
React.createElement(
"div",
null,
React.createElement(
"div",
{ align: "middle" },
React.createElement(
"div",
{ id: "head" },
React.createElement("img", { id: "pic", align: "middle", "max-width": "100%", src: "title_pic.png" }),
React.createElement(
"div",
{ align: "left", className: "big" },
React.createElement(
"div",
null,
React.createElement(
"span",
null,
"Dine with the Best"
),
React.createElement(
"div",
{ className: "words" },
React.createElement(
"span",
null,
"BonApp connects you with limited-time, exclusive meals and events offered by the city’s best chefs.",
React.createElement("br", null),
React.createElement("br", null),
React.createElement("br", null),
React.createElement(
"button",
{ type: "button" },
"JOIN BONAPP"
)
)
)
)
)
)
)
)
);
}
});
ReactDOM.render(React.createElement(Gallery, null), document.getElementById("Gallery"));
var WhatsNew = React.createClass({
displayName: "WhatsNew",
render: function render() {
return React.createElement(
"div",
{ className: "dark_bg_color" },
React.createElement(
"h2",
{ style: { marginBottom: 30 } },
React.createElement(
"span",
null,
"What's New"
)
),
React.createElement(
"div",
{ className: "autoplay" },
React.createElement("img", { src: "whatsnew0.png" }),
React.createElement("img", { src: "whatsnew1.png" }),
React.createElement("img", { src: "whatsnew0.png" })
)
);
}
});
ReactDOM.render(React.createElement(WhatsNew, null), document.getElementById("whatsnew"));
var BonEvents = React.createClass({
displayName: "BonEvents",
render: function render() {
return(
/* Events */
React.createElement(
"div",
{ id: "events", className: "dark_bg_color" },
React.createElement(
"div",
{ className: "box" },
React.createElement(
"div",
{ className: "box-text" },
React.createElement("div", { className: "horizontal-line" }),
React.createElement(
"div",
null,
React.createElement("div", { className: "horizontal-line" }),
React.createElement(
"p",
null,
"LES BON CADEAUX"
)
),
React.createElement("div", { className: "horizontal-line" })
)
),
React.createElement(
"h2",
null,
React.createElement(
"span",
null,
"Bon Events"
)
),
React.createElement("div", null)
)
);
}
});
ReactDOM.render(React.createElement(BonEvents, null), document.getElementById("events"));
var IOS = React.createClass({
displayName: "IOS",
render: function render() {
/* IOS */
return React.createElement(
"div",
null,
React.createElement(
"h2",
null,
React.createElement("span", null)
)
);
}
});
ReactDOM.render(React.createElement(IOS, null), document.getElementById("advertiseApp"));
var Footer = React.createClass({
displayName: "Footer",
render: function render() {
return(
/* Footer */
React.createElement(
"div",
null,
React.createElement(
"div",
{ className: "footer_center" },
React.createElement(
"div",
null,
React.createElement(
"ul",
null,
React.createElement(
"li",
null,
"ABOUT"
),
React.createElement(
"li",
null,
"PRESS"
),
React.createElement(
"li",
null,
"CONTACT"
),
React.createElement(
"li",
null,
"SUPPORT"
),
React.createElement(
"li",
null,
"BONAPP FOR RESTAURANTEURS"
)
)
)
),
React.createElement(
"div",
{ className: "legal_center" },
React.createElement(
"div",
null,
React.createElement(
"ul",
null,
React.createElement(
"li",
null,
"Copyright © 2016 BonApp Dining Inc."
),
React.createElement(
"li",
null,
"Privacy Policy"
),
React.createElement(
"li",
null,
"Legal"
)
)
)
)
)
);
}
});
ReactDOM.render(React.createElement(Footer, null), document.getElementById("footer"));
In order for the client's browser to execute your javascript code, it has to be requested by the client's browser. That means putting a <script> tag in your HTML document to load the file, something like this:
<script src="https://example.com/my-react-code.js"></script>
Without that, your code is just sitting on your server doing nothing.
But there's another step first: as #Vijay noted in the comments, your code needs to be transpiled. What does that mean? Well, look at your code: it's written in EcmaScript 2015, a recent dialect of Javascript that is not well supported by browsers. In order to ensure that your code works on most browsers, you need to translate it from the new dialect to something that browsers will be able to execute. This is called transpiling. Babel is one package that can do this; there are others as well. If you decide to use Babel, have a look at the setup page which gives detailed instructions on how to use Babel in a wide variety of different environments.
Edit
How to use Babel to transpile your code is a big question. I'll give a very brief example.
So imagine that you have the code given above saved in a file called src/my-react-code.js and you want to transpile it to a new file called dist/my-react-code.js. Imagine also that you have installed Babel locally with npm install --save-dev babel-cli. To transpile the source file, do this:
./node_modules/.bin/babel src -d dist
This will take your source file, transpile it (ie. translate it from new ES2015 syntax to old Javascript syntax), and save the result in dist/my-react-code.js.
However, this will not work given just the information in this question & answer. There are a couple more things you need:
Your source file needs to import the React package with a line like import React from 'react'; at the top; there may be other packages that need to be imported too.
Babel can be configured in a lot of different ways. You'll need to include some additional Babel plugins. Off the top of my head, I think you'll need to do npm install --save-dev babel-preset-es2015 babel-preset-react babel-preset-stage-0. These packages tell Babel what kind of source code to expect - in your case, it's ES2015 code with React components embedded in it (the stage-0 package includes a set of packages that are particular parts of the ES2015 standard). You'll also need to create a .babelrc configuration file containing:
{
"presets": ["es2015", "react", "stage-0"]
}
This tells Babel which plugins to use.
This command-line usage of Babel is documented at https://babeljs.io/docs/setup/. Pick your environment from the buttons at the top - I selected the first one, CLI.
Once you have a successful transpilation, take a look at the difference between the original source code and the final code - you'll see that Babel adds a lot of boilerplate code, basically rewriting features that aren't available in most browsers using "old" Javascript.
As mentioned above, there are many ways to configure Babel. I've given the simplest, but also the most cumbersome. Every time you change your source code, you will need to re-transpile it so your server sends it to the client. There are many tools for bundling all your Javascript together (browserify, webpack, etc.), automating the build process (grunt, gulp, etc.), testing your code (mocha, jest, etc.). You should spend some time imagining what your ideal work flow and environment would be and see if you can put it together using these tools.

React render not working with createElement

My simple component:
var AddProductForm = React.createClass({
render: function(){
return(
<form >
<input type='text' placeholder='lablbalbalbal'/>
</form>
)
}
})
My second component that I want to 'render' the first component in some determined div via onClick:
var HeaderAction = React.createClass({
render: function(){
return(
<button type="button" onClick={this.handleClick} className="btn border-slate text-slate-800 btn-flat"><i className={this.props.icon + " position-left"}></i>{this.props.name}</button>
)
},
handleClick: function(){
var component = React.createElement(this.props.action.component);
ReactDOM.render( component, document.getElementById('content'));
}
})
When I click my 'HeaderAction' component, an error occurs:
Uncaught Invariant Violation: Invalid tag:
The console.log() from my 'component' :
Object {$$typeof: Symbol(react.element), type: "<AddProductForm/>", key: null, ref: null, props: Object…}
$$typeof: Symbol(react.element)
_owner: null
_self: null
_source: null
_store: Object
key: null
props: Object
ref: null
type: "<AddProductForm/>"
__proto__: Object
If in the render call I change 'component' for "<AddProductForm/>" it works fine, but using the createElement for instantiate the object before the render doesn't.
var AddProductForm = React.createClass({
render: function(){
return(
<form >
<input type='text' placeholder='lablbalbalbal'/>
</form>
)
}
})
var HeaderAction = React.createClass({
render: function(){
return(
<button type="button" onClick={this.handleClick}</button>
)
},
handleClick: function(){
var component = React.createElement(AddProductForm);
ReactDOM.render( component, document.getElementById('content'));
}
})
var mount = document.getElementById('container');
ReactDOM.render(React.createElement(HeaderAction), mount)
I do not have an answer for you, however this seems to work. I do not know what this.props.action.component is in your case. I have created a small fiddle. Maybe we can work this out. https://jsfiddle.net/walkerrsmith/htaca7fa/

React renders text slower than style change - Alert component

I'm learning react. In the below Alert component I'm updating a simple alert message and setting the opacity to 1 and then fading it out with a CSS transition. This is in a simple to do app to get ramped up on react.
The issue I'm having is when I update the alert text this.props.message the previous message text shows for a fraction of a second after opacity is set to 1, before the new message replaces it. It is very quick but it seems like there is a race condition as the DOM or React renders the text change slower than the style change. Let me know if there is a way I can omit the hiccup and set opacity after the text message has changed. Thanks.
var TodoApp = React.createClass({
getInitialState: function() {
return {
items: [],
alert: { message: '', success: null }
};
}
genericMethod: function() {
...
this.setState({ alert: { message: message, success: true } });
...
},
...
render: function() {
return (
<div>
<Alert message={this.state.alert.message} success={this.state.alert.success} />
<ItemInput onItemSubmit={this.addItem} />
<ItemList items={this.state.items} deleteItem={this.deleteItem} toggleComplete={this.toggleComplete} />
</div>
);
}
});
...
var Alert = React.createClass({
delayTime: 1000,
getInitialState: function() {
return {
visible: false
};
},
componentWillReceiveProps: function() {
this.setState({ visible: true }, function() {
this.setTimer();
});
},
setTimer: function() {
setTimeout(function(argument) {
this.setState({ visible: false });
}.bind(this), this.delayTime);
},
render: function() {
var style = {
opacity: (this.state.visible ? 1 : 0),
transition: 'opacity '+(this.state.visible ? 0 : this.delayTime)+'ms'
};
var alertClass = 'alert'+(this.props.success ? ' success' : ' error');
return (
<div className={alertClass} style={style}>
{this.props.message}
</div>
);
}
});
The solution was to remove the alert state from the top level Todo class. So { items: [ ], alert: { message: '', success: null } } became just { items: [ ] } and then call a method on the child Alert component from my Todo component with <Alert ref="alert" /> and this.refs['alert'].triggerAlert(message, true); (as seen in this SO answer React.js - access to component methods) instead of watching componentWillReceiveProps in the Alert component. This made it so I was not prematurely rendering the Alert component before the new message was set every time the Todo items were added or updated.

Categories