I've been trying to get this to work for ages, but no matter what I do the directive can't find my react component.
These are the files I'm including:
<script src="bower_components/react/JSXTransformer.js"></script>
<script src="bower_components/react/react-with-addons.js"></script>
<script src="bower_components/ngReact/ngReact.min.js"></script>
<script src="node_modules/babel-core/browser.js"></script>
<script src="static/react-components.min.js" type="text/babel"></script>
<script src="static/main.min.js"></script>
Where my components are inside the react-components.min.js file, and all of my angular code is inside main.min.js.
It's stated that you (might(?)) need to use an in browser transformator for this directive to work, so I tried that using babel, but that also doesn't work.
This is my react component:
<react-component name="Chat" watch-depth="reference"></react-component>
And in the react-components.min.js file I got a component called 'Chat':
var Chat = React.createClass({
render: function() {
return <footer className="chat chat--dark">Hello John</footer>;
}
});
core.value('Chat', Chat); // My application is bound to the core module
But it doesn't find it.. What could be wrong because no one else seems to have this issue?
JSX Compilation Issue
I believe it is a compilation error. I ran your code through an online compiler (https://babeljs.io/repl/) swap your current component code out with the block below and see if it works:
"use strict";
var Chat = React.createClass({
displayName: "Chat",
render: function render() {
return React.createElement(
"footer",
{ className: "chat chat--dark" },
"Hello John"
);
}
});
core.value('Chat', Chat); // My application is bound to the core module
JSXTransformer is deprecated you should add in a build step that uses Babel.
https://facebook.github.io/react/blog/2015/06/12/deprecating-jstransform-and-react-tools.html
Check out my blog post for the breakdown on adding JSX and ES6 support.
http://blog.tylerbuchea.com/migrating-angular-project-to-react/
Related
I have the following in my index.js file
class PersonProfileBadge extends React.Component {
constructor(props) {
super(props);
this.alias = this.props.alias;
}
render() {
return e(
'img',
{
src: `https://internal-cdn.foo.com/somepath/?uid=${this.alias}`,
className: 'profile_photo'
}
);
}
}
and it works when I render it like so
ReactDOM.render(
e(PersonProfileBadge, {'alias': 'stupidfatcat'}),
navProfilePicture
);
But I'm trying to get JSX support since it makes the code look generally much more readable
ReactDOM.render(
<PersonProfileBadge alias='stupidfatcat' />,
navProfilePicture
);
But I'm getting this error:
Uncaught SyntaxError: Unexpected token '<'
In my index.html I have the following imports
<script src="internalcdnpathto/static/react/react.production.min.js"></script>
<script src="internalcdnpathto/static/react-dom/react-dom.production.min.js"></script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script src="/static/index.js"></script>
Not entirely sure what I'm doing wrong or where to even get started.
You generally want to add a preprocessor in order to use JSX. The quickest way to try JSX in your project is to add this tag to your page:
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
Now you can use JSX in any tag by adding type="text/babel" attribute to it. This approach is fine for learning and creating simple demos. However, it makes your website slow and isn’t suitable for production.
Read more in the official React docs.
You need babel to compile your code from JSX to javascript from this:
ReactDOM.render(
<PersonProfileBadge alias='stupidfatcat' />,
navProfilePicture
);
to that:
ReactDOM.render(
e(PersonProfileBadge, {'alias': 'stupidfatcat'}),
navProfilePicture
);
You should utilize a bundler like webpack so you parse your code everytime you change something, i'd suggest creating a project via create-react-app
or take a look at Babel Standalone
I've created an onClick handler in a very simple React function component:
export default function MyButton() {
return (
<button
onClick={() => {
console.log('test');
}}
>
Button
</button>
);
}
Now the weird part: no matter what browser I use, the event is not firing. I've created such a component hundreds of times and everything was good, until now.
For everyone else this code works, as it was intended.
I cannot share the whole project or an example repository. It's really nothing but a simple React app you see everywhere.
What could be the reason for why it's not working on my system?
EDIT:
The error was somehow within yarn. I called webpack-dev-server -d source-map --mode=development for development and I am using "webpack-dev-server": "^4.0.0-beta.0". I think the cache could've gotten corrupted somehow.
To fix it, I removed my output directory and started the script with npm instead of yarn. This way it worked, even when I use yarn again.
I really don't know why this happened. Would be happy to know why.
I also faced the same issue and the reason of the issue (in my case , probably yours ) is HtmlWebpackPlugin, HtmlWebpack Plugin is adding a addition script tag of bundle in head tag of index.html.
my html
<html>
<head>
<title>my-react-app</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
htmlwebpackplugin generated html
<html>
<head>
<title>my-react-app</title>
<script defer src="bundle.js"></script></head>
<body>
<div id="root"></div>
<script src="bundle.js"></script>
</body>
</html>
because of this additional script tag, there was a problem in react (i read a post on reddit regarding to this problem and he also have multiple script of same bundle and he was having the same problem), i solved it by deleting my script tag, but we can use copywebpack plugin to just copy html. Or other solution is to configure htmlwebpackplugin suck a way that it will not inject any addition tags
...
new HtmlWebpackPlugin({
name: "index.html",
inject: false,
template: path.resolve(__dirname, "public/index.html"),
}),
...
Use named function instead of anonymous function. Named functions are very useful for identifying what functions caused errors during development as well as when retrieving logs from your users.
import React from "react";
export default function MyButton() {
const handleChange = () => {
console.log("test");
};
return <button onClick={handleChange}>Button</button>;
}
It is a good practice to name-all-functions for a better developer debugging (and development) experience which anonymous function does not provide.
For more clarification between Named and Anonymous function Learn the benefits of Named vs Anonymous function here
Try typing your function as React.FC.
Create a typescript (tsx) file and use the upcoming code:
import React from "react";
export const MyButton: React.FC = () => {
return (
<button
onClick={() => {
console.log("test");
}}
>
Button
</button>
);
};
Note that using this code, you are typing the component making sure that your function is typed as React.FunctionComponent.
Did you import this in your file, if not then add this tine on top
import React from 'react';
I am newbie to React.js. For learning purpose just I created the login page which you can find here.
In my local project also, I used the CDN for babel and react, like below.
<script src="https://unpkg.com/react#latest/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#latest/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
I want to use one of the form validation plugin into this example. But when I tried to include this (as per the document)
import ValidateableForm from 'react-form-validate';
I am getting the following error.
Uncaught ReferenceError: require is not defined
I went through few posts and they said that I have to use webpack or Rollup or Browsify .I am not sure how to include this in to my current local project setup. Since I am not using npm (in learing I dont want to use npm)
I dont know how to include that plugin into my project
If it is already coming with external site , I cant able to figure
it out what is the issue.
Please help me to resolve the issue.
This is an old question, but at least currently, this is completely possible with conventional script tags. This article is very helpful for understanding development setup alternatives for React
In that article it details bringing in React, React-Dom, and Babel via script tags for development, like this (I'm linking to npm downloaded packages, but that isn't necessary):
<script src="/node_modules/react/umd/react.development.js"></script>
<script src="/node_modules/react-dom/umd/react-dom.development.js"></script>
<script src="/node_modules/#babel/standalone/babel.min.js"></script>
In my case, I needed to bring in the react-notification-system plugin:
<script src="/node_modules/react-notification-system/dist/react-notification-system.min.js"></script>
(Note the use of the compiled 'dist' version)
Once that was included I was able use it like this:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.notificationSystem = new ReactNotificationSystem();
}
addNotification = event => {
event.preventDefault();
const notification = this.notificationSystem.current;
notification.addNotification({
message: 'Notification message',
level: 'success'
});
};
render() {
return (
<div>
<button onClick={this.addNotification}>Add notification</button>
<ReactNotificationSystem ref={this.notificationSystem} />
</div>
);
}
}
I had to look in the plugin's code to know that the name: ReactNotificationSystem would be available, much of the plugin documentation that you find is not written with this type of dev setup in mind, but it does work.
I'm using highcharts-ng, trying to do client side pdf download and keep getting Unsupported export format on this platform: application/pdf. If I use the highcharts server to generate the pdf it works fine.
options: {
exporting: {
type: 'application/pdf'
}
},
func: function() {
// button handler
$('#vehicle-conversion-pdf-btn').click(function () {
var chart = $('#vehicle-conversion').highcharts();
chart.exportChart();
});
}
I'm also loading the plugin last.
I had a problem almost like this.
I had been imported "highcharts-export-clientside.js" to my web page, but it didn't work. (from this documentation )
my problem fixed with this line :
<script src="http://code.highcharts.com/modules/offline-exporting.js"></script>
Altogether you must have this imports in your html file :
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="http://code.highcharts.com/modules/offline-exporting.js"></script>
I'm very loosely following the example here up until the point where it starts running the dev server.
I have a test React component (in scripts/test.jsx):
/** #jsx React.DOM */
var React = require('react');
var Test = React.createClass({
render: function(){
return <h1>HI!</h1>
}
});
module.exports = Test;
I have a webpack.config where I'm using the jsx loader against the source directory (It's basically the same as the one in the example except I'm adding the library properties).
I run webpack and it generates the bundle file like I expect, however, when I try to use the component in an html file (after including the bundle.js script reference) I get the following in console: "Uncaught ReferenceError: Test is not defined".
The HTML contains the following:
<div id="hi">
</div>
<script type="text/jsx">
/** #jsx React.DOM */
React.renderComponent(
<Test />,
document.getElementById('hi')
);
</script>
Am I doing something incorrect to use a component that is defined in CommonJS style against an html page that isn't technically using a module loader (I'm trying to treat this test as if it's someone who is trying to load the component without any type of structured module loader)?
The output of the webpack is available here
EDIT 2: The full example code is available as a github repo
Yeah, you'd be better off following the example and requiring Test from a .jsx file rather than inlining it in the HTML.
Otherwise, Test needs to be exported as a global, so you'd need to follow similar conventions to the browserify --standalone flag, which looks to be something like this:
output: {
library: "Test",
libraryTarget: "umd"
}
http://webpack.github.io/docs/webpack-for-browserify-users.html#standalone
Edit: After looking at your GH repo, you have:
<script src="bundle.js" type="text/js"></script>
instead of
<script src="bundle.js" type="text/javascript"></script>
so it wasn't loading bundle at all. Further, you can't have 2 separate copies of react, the way you have it currently you're requiring React from within webpack, and then you're also loading it on the page. You should either export a function which takes the React object, or use the global to be able to use it outside of the bundle.
For example this would work:
/** #jsx React.DOM */
module.exports = function(React) {
var Test = React.createClass({
render: function(){
return <h1>HI!!</h1>
}
});
return Test;
};
and then:
/** #jsx React.DOM */
React.renderComponent(
Test(React)(),
document.getElementById('hi')
);
or this
/** #jsx React.DOM */
var Test = React.createClass({
render: function(){
return <h1>HI!!</h1>
}
});
module.exports = Test;
and then:
/** #jsx React.DOM */
React.renderComponent(
<Test />,
document.getElementById('hi')
);
Though I can't imagine most folks consuming a React package are going to be loading it with a script tag, and you generally don't want globals, so it's probably best to just use the CommonJS style require and let people figure out shimming or whatever.