Reputation: 1756
I have a simple React component that I am trying to incorporate into a web page. The component looks as follows (in file like_button.js
). This JSX I am compiling using babel v6.4.1.
'use strict';
import React, {Component} from 'react';
const e = React.createElement;
class LikeButton extends Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return (
<button onClick={() => this.setState({ liked: true })}>
Like
</button>
);
}
}
const frmReg = document.querySelector('#frmReg');
ReactDOM.render(e(LikeButton), frmReg)
The HTML page (index.php) that I am trying to consume this, looks as follows.
<html>
<head>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
</head>
<body>
<div id="frmReg"></div>
</body>
<!-- <script src="assets/js/like_button.js"></script> -->
<script src="assets/js/admincomponent.js"></script>
</html>
My package.json
file looks as follows.
{
"name": "react_dt",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"babel": "^6.5.2",
"babel-cli": "^6.9.0",
"babel-plugin-transform-es2015-modules-amd": "^6.24.1",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1"
}
}
Also have included .babelrc
included in the project root, which appears as follows.
{
presets: ["es2015", "react"],
plugins: ["transform-es2015-modules-amd"]
}
However, when I try to run this in the browser, I don't see a thing in the page. Further, in the dev tools console, I am having the error Uncaught SyntaxError: Unexpected identifier
, with the import React, { Component } from 'react';
statement highlighted.
I tried the same without the import statement and got it to work flawlessly. So basically it boils down to a problem with the import
. Upon research, I have read that this is a problem from ES5 to ES6(ES2015). Further, I have found about 5 odd questions on the same issue, that which none of their solutions helped me to find the solution.
What is wrong? Why won't it let me do the import?
Upvotes: 0
Views: 561
Reputation: 1823
Please install the react
and react-dom
package. When you are importing the the package that means package is installed in node_modules
. It will search the package in node_modules
folder and then show error if not found.
Are you compiling your javascript file using babel? Please use babel compiled javascript in the project. You can use babel-node for compiling your javascript to es5
Upvotes: 2