I have a html file, .js file and .jsx file. I have added/imported both .js and .jsx files in html file.
.js file has a function to return a div tag.
I would like to render the value returned by this function to root div tag in html.
I am thinking of invoking JS function within JSX and render the value returned by this JS function using ReactDOM.render.
Is it possible to invoke a JS function from .jsx file?
index.html has below content
<!DOCTYPE html>
<html>
<head>`enter code here`
<meta charset="UTF-8" />
<title>Hello World</title>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
<script type="text/babel" src="test.jsx"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
test.js has below content
function alertme() {
return "<div><h1>Hello, world!</h1></div>"
}
test.jsx has below content
function tick() {
const element = (
<div>{alertme()}</div>
);
ReactDOM.render(
element,
document.getElementById('root')
);
}
tick();
Instead of displaying hello world it is displaying complete html tag
What could be done fix this?
Yes you can access the function of .js file in the .jsx file.
You just have to import the .js file the file where you want to use the method.
For example:
import { connect } from 'react-redux';
And now in your jsx file you can use the connect method with required parameters.
Above import is just for example.
Hope it helps
You can use dangerouslySetInnerHTML function provided by react to turn a string in to an React element.https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.
function alertme() {
return "<div><h1>Hello, world!</h1></div>"
}
function tick() {
const element = <div dangerouslySetInnerHTML={{__html: alertme()}}></div>;
ReactDOM.render(
element,
document.getElementById('root')
);
}
tick();
<!DOCTYPE html>
<html>
<head>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
Related
I am currently working on a react application and everything was working fine until recently when I noticed that all the external scripts I defined in the public/html no longer works when rendering pages using react-router-dom, but works fine when I call the pages directly.
These is my html file body tag:
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/plugins.bundle.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/scripts.bundle.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/intro.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/widgets.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/chat.js"
></script>
<script
defer
type="text/javascript"
src="%PUBLIC_URL%/assets/js/modals/create-app.js"
></script>
</body>
Everthing works perfectly if I render the page this way:
const App = () => {
return (
<UserDashboard/>
);
};
export default App;
But when using react-router-dom, it doesnt throw any errors but nothing works
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<UserDashboard />/>
<Route path="/login" element={<Login />} />
</Routes>
</BrowserRouter>
);
My folder structure
Please does anyone know why this is happening and how can I fix it, cause I'm using a template and those scripts are necessary for the template to function properly.
I'm beginning to think this has to with react-router-dom version 6, cause I have not encountered this problem when working on previous projects. Its the only thing I can suspect would downgrading the react-router-dom be a bad idea?
I had a similar issue where I needed to load scripts in html tags in an app created from create-react-app library and found that I needed to put them in the body, afer rootand use the deferkeyword as below:
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/CCapture.js'></script>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/gif.js'></script>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/webm-writer-0.3.0.js'></script>
<script defer type='text/javascript' src='%PUBLIC_URL%/ccapture/download.js'></script>
Can't remember if using the %PUBLIC_URL% variable was part of the solution or I just used it because the template had similar.
The script paths are relative to the current URL path. They probably work without issue if/when the app loads and you are on the root "/" route, but have issue when on any sub-route.
Specify absolute paths in your public directory instead.
<script src="/assets/js/plugins.bundle.js"></script>
<script src="/assets/js/scripts.bundle.js"></script>
<script src="/assets/js/intro.js"></script>
<script src="/assets/js/widgets.js"></script>
<script src="/assets/js/chat.js"></script>
<script src="/assets/js/modals/create-app.js"></script>
I had a similar issue. I'm using Electron with webpack and was able to resolve this by adding a custom file protocol to handle custom requests for static files. Added within the window creation handler. This may be of help.
import { app, BrowserWindow, session } from 'electron';
//...
session.defaultSession.protocol.registerFileProtocol('asset', (request, callback) => {
const fileUrl = request.url.replace('asset://', '');
const filePath = path.join(app.getAppPath(), '.webpack/assets', fileUrl);
callback(filePath);
});
I just got started using React, so this is probably a very simple mistake, but here we go. My html code is very simple:
<!-- base.html -->
<html>
<head>
<title>Note Cards</title>
<script src="http://<url>/react-0.11.2.js"></script>
<!-- <script src="http://<url>/JSXTransformer-0.11.2.js"></script> -->
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<script src="{% static "build/react.js" %}"></script>
</head>
<body>
<h1 id="content">Note Cards</h1>
<div class="gotcha"></div>
</body>
</html>
Note that I am using Django's load static files here. (My JavaScript is a bit more complex, so I won't post it all here unless someone requests it.) This is the line with the error:
React.renderComponent(
CardBox({url: "/cards/?format=json", pollInterval: 2000}),
document.getElementById("content")
);
After which I get the 'target container is not a DOM element error' yet it seems that document.getElementById("content") is almost certainly a DOM element.
I looked at this stackoverflow post, but it didn't seem to help in my situation.
Anyone have any idea why I'd be getting that error?
I figured it out!
After reading this blog post I realized that the placement of this line:
<script src="{% static "build/react.js" %}"></script>
was wrong. That line needs to be the last line in the <body> section, right before the </body> tag. Moving the line down solves the problem.
My explanation for this is that react was looking for the id in between the <head> tags, instead of in the <body> tags. Because of this it couldn't find the content id, and thus it wasn't a real DOM element.
Also make sure id set in index.html is same as the one you referring to in index.js
index.html:
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
index.js:
ReactDOM.render(<App/>,document.getElementById('root'));
webpack solution
If you got this error while working in React with webpack and HMR.
You need to create template index.html and save it in src folder:
<html>
<body>
<div id="root"></div>
</body>
</html>
Now when we have template with id="root" we need to tell webpack to generate index.html which will mirror our index.html file.
To do that:
plugins: [
new HtmlWebpackPlugin({
title: "Application name",
template: './src/index.html'
})
],
template property will tell webpack how to build index.html file.
Just to give an alternative solution, because it isn't mentioned.
It's perfectly fine to use the HTML attribute defer here. So when loading the DOM, a regular <script> will load when the DOM hits the script. But if we use defer, then the DOM and the script will load in parallel. The cool thing is the script gets evaluated in the end - when the DOM has loaded (source).
<script src="{% static "build/react.js" %}" defer></script>
Also, the best practice of moving your <script></script> to the bottom of the html file fixes this too.
I had encountered the same error with React version 16. This error comes when the Javascript that tries to render the React component is included before the static parent dom element in the html. Fix is same as the accepted answer, i.e. the JavaScript should get included only after the static parent dom element has been defined in the html.
For those that implemented react js in some part of the website and encounter this issue.
Just add a condition to check if the element exist on that page before you render the react component.
<div id="element"></div>
...
const someElement = document.getElementById("element")
if(someElement) {
ReactDOM.render(<Yourcomponent />, someElement)
}
Also you can do something like that:
document.addEventListener("DOMContentLoaded", function(event) {
React.renderComponent(
CardBox({url: "/cards/?format=json", pollInterval: 2000}),
document.getElementById("content")
);
})
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
One of the case I encountered the same error in a simple project. I hope the solution helps someone.
Below code snippets are sufficient to understand the solution :
index.html
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
someFile.js : Notice the line const portalElement = document.getElementById("overlays"); below :
const portalElement = document.getElementById("overlays");
const Modal = (props) => {
return (
<Fragment>
{ReactDOM.createPortal(<Backdrop />, portalElement)}
{ReactDOM.createPortal(
<ModalOverlay>{props.children}</ModalOverlay>,
portalElement
)}
</Fragment>
);
};
I didn't have any element with id = "overlays" in my index.html file, so the highlighted line above was outputting null and so React wasn't able to find inside which element it should create the portal i.e {ReactDOM.createPortal(<Backdrop />, portalElement)} so I got below error
I added the div in index.html file and the error was gone.
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="overlays"></div>
<div id="root"></div>
</body>
I got the same error i created the app with create-react-app but in /public/index.html also added matrialize script but there was to connection with "root" so i added
<div id="root"></div>
just before
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/ materialize.min.js"></script>
And it worked for me .
Target container is not a DOM element.
I achieved this error with a simple starter app also.
// index.js
ReactDOM.render(
<Router>
<App />,
document.getElementById('root')
</Router>
);
Solution:
Syntax errors can cause this error. I checked my syntax and wrapped my <App /> properly.
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root')
);
In my case, I forget to add this line to the index.js file
document.getElementById('root')
and I forget to import react-dom import ReactDOM from 'react-dom'; so you can use ReactDOM later in the same file
Hope this will be helpful for you
I am very much new to React. The following is my first script.
But I am getting the following error.
Uncaught SyntaxError: Unexpected token <
I have even searched through google/SO. But I couldn't get it to work.
<!DOCTYPE html>
<html>
<head>
<title>First React App</title>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const name = 'John doe'
const handle = '#john_doe'
function NameComponent (props){
return <h1>{props.name}</h1>;//The problem is here using JSX syntax
}
function HandleComponent(props){
return <h3>{props.handle}</h3>;
}
function App(){
return (
<div id="container">
<NameComponent name={name}/>
<HandleComponent handle={handle}/>
</div>
);
}
ReactDOM.render(<App />,document.getElementById('app'));
</script>
</body>
</html>
To make your code work as it is currently, you just need to add type="text/babel" to the script tag that contains the code that you intend to transpile using babel.
From the babel docs:
When loaded in a browser, #babel/standalone will automatically compile and execute all script tags with type text/babel or text/jsx
Working code with just this change
<html>
<head>
<title>First React App</title>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script type="text/babel">
const name = 'John doe'
const handle = '#john_doe'
function NameComponent (props){
return <h1>{props.name}</h1>;//The problem is here using JSX syntax
}
function HandleComponent(props){
return <h3>{props.handle}</h3>;
}
function App(){
return (
<div id="container">
<NameComponent name={name}/>
<HandleComponent handle={handle}/>
</div>
);
}
ReactDOM.render(<App />,document.getElementById('app'));
</script>
</body>
</html>
Though this works, using create-react-app or codesandbox is generally much simpler for beginners.
In order to have a bare minimum setup with react (with no compilation step), you need either to use React.createElement syntax instead of JSX tags (check https://reactjs.org/docs/add-react-to-a-website.html), or use something like htm
Personally I would just use Create React App to help with the initial setup. This will configure babel (among a lot of other things) for you and do the proper JSX transpilation. Although in the future it will be good for you to know exactly whats under the hood of create-react-app and maybe make your own setup.
Simply install babel using npm with this command:
npm install --save #babel/standalone
Also include this line in your HTML file:
<script type="text/babel" src="like_button.js"></script>
Example code:
<script src="https://unpkg.com/react#17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script type="text/babel" src="like_button.js"></script>
if you have script tag in your index.html give it a type="text/babel"
If that didn't fix it try:
Removing the homepage line entirely from the package.json in the react app directory fixed it somehow.
The following Simple ReactJS code is not working. Newbie needs help please!
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ReactJS Test</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-standalone#6.15.0/babel.min.js"></script>
</head>
<body>
<div id="container"></div>
<script type="text/babel">
var currentLocation = window.location;
ReactDOM.render(
<div>
<p>currentLocation : {currentLocation}</p>
</div>,
document.getElementById('container')
);
</script>
</body>
</html>
And Chrome console shows helpless error messages like this:
react-dom.production.min.js:67 Uncaught Error: Minified React error #31; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=31&args[]=http%3A%2F%2Fxxxxxxx.com%3A8080%2F_test%2Fsitetest_new.jsp&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
at m (react-dom.production.min.js:67)
at qb (react-dom.production.min.js:82)
at z (react-dom.production.min.js:87)
at C (react-dom.production.min.js:89)
at react-dom.production.min.js:94
at g (react-dom.production.min.js:43)
at f (react-dom.production.min.js:43)
at beginWork (react-dom.production.min.js:48)
at e (react-dom.production.min.js:18)
at k (react-dom.production.min.js:19)
Thanks in advance!
window.location returns an object. You can't embed a standalone object in JSX. You can only embed JavaScript expressions.
Try using JSON.stringify() to convert your object to a string.
You can run the snippet below or check out this CodePen Demo.
var currentLocation = window.location;
ReactDOM.render(
<div>
<p>currentLocation : {JSON.stringify(currentLocation)}</p>
</div>,
document.getElementById('container')
);
<div id="container"></div>
<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>
Note: If you just want a string value from your window.location object (e.g. href), you don't need JSON.stringify().
You could simply use window.location.href directly in your JSX (or set var currentLocation = window.location.ref;) - example.
When I'm editing the below example HTML page in Visual Studio Code (borrowed from Facebook's React tutorial and slightly edited), if I write any Javascript code in the script block, it is not syntax highlighted. But if I change the script block type to "text/javascript" then the syntax highlighting works. But then any React-y/JSX code doesn't work as it is wired to work through Babel.
Is there any way to have the script tag "type" attribute set to "text/babel" and at the same time have proper syntax highlighting in Visual Studio Code?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React Tutorial</title>
<script src="https://npmcdn.com/react#15.3.0/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom#15.3.0/dist/react-dom.js"></script>
<script src="https://npmcdn.com/babel-core#5.8.38/browser.min.js"></script>
<script src="https://npmcdn.com/jquery#3.1.0/dist/jquery.min.js"></script>
<script src="https://npmcdn.com/remarkable#1.6.2/dist/remarkable.min.js"></script>
</head>
<body>
<div id="content"></div>
<script type="text/babel">
ReactDOM.render(
<div>Hello world!</div>,
document.getElementById('content')
);
</script>
</body>
</html>
I found a solution to this now.
Open up: (VS code home dir)\resources\app\extensions\html\syntaxes\html.json, and edit the regex for the script tag. That fixed the issue for me.
Well this is a workaround, probably will be better to change this in a post build process, but I found an easy way to do it with this new feature TagHelpers which will help to replace the javascript value by babel
So add a file TagHelpers/ScriptTagHelper.cs
[HtmlTargetElement("script", Attributes = "to_babel")]
public class ScriptTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.Attributes.SetAttribute("type", "text/babel");
}
}
In your page Index.cshtml
<script type="text/javascript" to_babel>
And dont forget to import TagHelpers in _ViewImports.cshtml or in your Index.cshtml
#using app1
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper *, app1
And voila! this render as babel.