I am new to ReactJS and all the solutions I found for this problem used npm cli and suggested to use babel-plugin-transform-es2015-modules-amd. However I am using CDN and here is my code:-
1] Here is my index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="js/react.production.min.js"></script>
<script src="js/react-dom.production.min.js"></script>
<script src="js/browser.min.js"></script>
</head>
<body>
<div id="root"></div>
</body>
<script src="js/components/hello.jsx"></script>
</html>
where browser.min.js is actually babel
and the other two react files are of version 16.5.2
2] And hello.jsx:-
import React from "react";
import { render } from "react-dom";
class App extends React.Component {
render() {
return (
<div>
<h1>Hello!</h1>
</div>
);
}
}
render(<App />, document.getElementById("root"));
This code throws an error at line 1 in hello.jsx saying "Uncaught SyntaxError: Unexpected identifier"
Any help is much appreciated. Thanks!
Since hello.jsx is JSX. You need to indicate this to the browser by setting the script attribute.
This is done by setting the script type attribute to text/babel e.g.
<script type="text/babel" src="js/components/hello.jsx"></script>
The babel standalone script traverses the DOM for scripts with this attribute and replaces them with their transpiled equivalents.
Edit
A couple of changes to hello.jsx
Remove the import statements
ReactDOM and React are globals in the context of window object.
Replace
render(<App />, document.getElementById("root"));
with
ReactDOM.render(<App />, document.getElementById("root"));
Related
I am self-learning react and I am just confused about a lot of things.
I thought that if I add React to my index.html via a script like the below:-
//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bill Details</title>
</head>
<body>
<div id="billTable"></div>
<script src="BillTable.js" type="text/javascript"></script> ------------- Problem Line 1
</script>
</body>
</html>
and this is my js file where I am trying to return react component
//BillTable.js
import React from "react";
import ReactDOM from "react-dom";
function BillTable() {
return <h1>HELLO TABLE</h1>;
}
ReactDOM.render(<BillTable/>, document.getElementById("billTable"));
when I try to open index.html directly in firefox or through express server I get the below error in console:-
Uncaught SyntaxError: import declarations may only appear at top level of a module.
I then got rid of this error by changing the script type in problem line 1 in index.html to
<script src="BillTable.js" type="text/babel"></script>
but then also my webpage is completely blank and even console is not showing any errors.
Please suggest how to solve this issue. I am right now trying to learn React with functional approach only, so if any changes are required to be done on the react side, please make them in the functional approach.
I don't think you have included the correct packages to handle React components and JSX yet. These packages react, react-dom, etc. are usually in a package.json and are required to tell the browser what tools will be used to run the code. These packages handle the "script" or components you create and places the elements constructed in your components to the DOM. You can solve this by loading react with additional script tags before your component's script tag. This will let the browser know how and what to use to run your react component. Also, in your function, it does not know that it is a React Component. Check out an explanation for why you would have to use React.createElement I have attached an example of using only an index.html page here:
example of using an index.html page
Your Component file:
"use strict";
function BillTable() {
return React.createElement("h1", "", "HELLO TABLE");
}
const domContainer = document.querySelector("#billTable");
const root = ReactDOM.createRoot(domContainer);
root.render(React.createElement(BillTable));
and your index.html:
<body>
<div id="billTable"></div>
<!-- Load your React packages -->
<script
src="https://unpkg.com/react#18/umd/react.development.js"
crossorigin
></script>
<script
src="https://unpkg.com/react-dom#18/umd/react-dom.development.js"
crossorigin
></script>
<!-- Load your React component. -->
<script src="BillTable.js"></script>
</body>
How to import a component in a script in HTML file?
What are the modifications to be done to make the following work?
And should the Babel libraries be added to the HTML file? (Webpack and React are already installed)
In car.js
class Car extends React.Component {
render() { return (<p>nice car</p>) }}
In page.html
...
<script type="text/babel">
import Car from "static/car.js" //<---------????????
ReactDOM.render(<Car />, document.querySelector("#root"));
</script>
do not need to import Car from "static/car.js" it will works in JS file.
for HTML need refarance like <script type="text/babel" src="static/car.js"></script>
<script src="static/car.js" type="text/babel"></script>
<script type="text/babel">
ReactDOM.render(<Car />, document.querySelector("#root"));
</script>
I am trying to use the import keyword in a .jsx file in my ASP.NET MVC 5 project. I want to be able to import other React components into another React component, however, when using the import keyword, I am getting the following error:
Uncaught SyntaxError: Cannot use import statement outside a module
Below is my code:
Index.cshtml:
#{
Layout = null;
}
<html>
<head>
<title>Hello React</title>
</head>
<body>
<div id="content"></div>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.development.js"></script>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
<script src="#Url.Content("~/Scripts/Tutorial.jsx")"></script>
</body>
</html>
Tutorial.jsx:
import Comment from '../Scripts/Comment.jsx';
class Tutorial extends React.Component {
render() {
return (
<div className="commentBox">
<h1>Homepage</h1>
<Comment />
</div>
);
}
}
ReactDOM.render(<Comment />, document.getElementById('content'));
Comment.jsx:
class Comment extends React.Component {
render() {
return (
<p>I am a comment!</p>
);
}
}
export default Comment;
If I do not have the imports or if I add the Comment class directly inside of the Tutorial.jsx, it runs fine, but that is not what I am looking for. I want to be able to have all my components in separate .jsx files and be able to import certain components into different ones. Ideas?
EDIT: Fixed export default Comment, however error is still appearing
The error "Cannot use import statement outside a module" results when a <script> element contains an import statement but the <script> element itself is not declared as an ECMAScript (or ES) module.
The import statement requires your script file Tutorial.jsx to be declared a module. Add the type attribute with the value module to the <script> tag.
See the first paragraph at the top of the page https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
The import statement cannot be used in embedded scripts unless such script has a type="module".
In your HTML page, change:
<script src="#Url.Content("~/Scripts/Tutorial.jsx")"></script>
to
<script type="module" src="#Url.Content("~/Scripts/Tutorial.jsx")"></script>
You need to export the Comment component properly. At the moment you are doing export default Test.
class Comment extends React.Component {
render() {
return (
<p>I am a comment!</p>
);
}
}
export default Comment; //<------- see here
I'm sorry to ask such a specific question but I'm working on a simple tutorial which introduces React with the following HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Separate</title>
</script>
</head>
<body>
<h1>Hello Separate</h1>
<div id="app"></div>
</body>
</html>
And a script to create a <p> within the div id ="app" using ReactDOM
ReactDOM.render(
<p>Rendered by React</p>,
document.getElementById("app")
)
I've provided the code in a fiddle here:
I don't understand why I'm getting the error Uncaught SyntaxError: Unexpected token < but think it's coming from the ReactDOM.render function, can anyone provide insight? Thank you!
Two issues with your code,
First
Your scripts are not proper. As per docs, you should add these scripts,
<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>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
Second
Might be you are writing your JS code in external JS file.
From the docs,
Now you can use JSX in any <script> tag by adding type="text/babel" attribute to it.
You need to add this script in your HTML file only,
<script type="text/babel">
ReactDOM.render(
<p>Rendered by React</p>,
document.getElementById("app")
)
</script>
Demo
As Emile Bergeron mentioned you're actually writing JSX, so you need 'build'
or transpile the code in regular JavaScript.
However if you're using just JSFiddle, they can transpile the code for you like this.
If you're working locally you can look into create-react-app as they mentioned or babel and webpack to build/bundle your files.
yes you might be right, you will might need to change: <p>Rendered by React</p> to either '<p>Rendered by React</p>' or "<p>Rendered by React</p>"
like this:
ReactDOM.render(
"<p>Rendered by React</p>",
document.getElementById("app")
)
you have to always enclose text or html in ".."
I have a react app which has an entrypoint of my app.jsx and I am adding segment.io to my build, however I would like to set it's API key as an process.env variable. I am having trouble with how to do this with webpack because my entry point is not the index.html.
I am trying to see if there is a way so I can (on the index.html) do something like this
<script type="text/javascript">
..segment script loading here + (process.env.MY_SEGMENT_KEY)}();
</script>
But I am not sure how to get it so I can process env variables at the index.html level.
In app.jsx I am toggling the code like :
if (process.env.MY_SEGMENT_KEY) {
....
}
and this works fine because I have access to the vars at this point. I would like to also conditionally load the script on the index.html. Anyone know if this is possible? Thanks!
Just load analytics in your JSX file as follow:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
if (process.env.MY_SEGMENT_KEY) {
window.analytics.load(process.env.MY_SEGMENT_KEY);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Your index.html file should look like that:
<!DOCTYPE html>
<html>
<head>
...
<title>My App</title>
<script type="text/javascript">
!function(){var analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","once","off","on"];analytics.factory=function(t){return function(){var e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(var t=0;t<analytics.methods.length;t++){var e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){var e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";var n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};analytics.SNIPPET_VERSION="4.0.0";
}}();
</script>
</head>
<body>
<div id="root">
</div>
</body>
</html>