Invariant Violation: _registerComponent(...): Target container is not a DOM element - javascript

I get this error after a making trivial React example page:
Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.
Here's my code:
/** #jsx React.DOM */
'use strict';
var React = require('react');
var App = React.createClass({
render() {
return <h1>Yo</h1>;
}
});
React.renderComponent(<App />, document.body);
HTML:
<html>
<head>
<script src="/bundle.js"></script>
</head>
<body>
</body>
</html>
What does this mean?

By the time script is executed, document element is not available yet, because script itself is in the head. While it's a valid solution to keep script in head and render on DOMContentLoaded event, it's even better to put your script at the very bottom of the body and render root component to a div before it like this:
<html>
<head>
</head>
<body>
<div id="root"></div>
<script src="/bundle.js"></script>
</body>
</html>
and in the bundle.js, call:
React.render(<App />, document.getElementById('root'));
You should always render to a nested div instead of body. Otherwise, all sorts of third-party code (Google Font Loader, browser plugins, whatever) can modify the body DOM node when React doesn't expect it, and cause weird errors that are very hard to trace and debug. Read more about this issue.
The nice thing about putting script at the bottom is that it won't block rendering until script load in case you add React server rendering to your project.
Update: (October 07, 2015 | v0.14)
React.render is deprecated, use ReactDOM.render
instead.
Example:
import ReactDOM from 'react-dom';
ReactDOM.render(<App />, document.getElementById('root'));

/index.html
<!doctype html>
<html>
<head>
<title>My Application</title>
<!-- load application bundle asynchronously -->
<script async src="/app.js"></script>
<style type="text/css">
/* pre-rendered critical path CSS (see isomorphic-style-loader) */
</style>
</head>
<body>
<div id="app">
<!-- pre-rendered markup of your JavaScript app (see isomorphic apps) -->
</div>
</body>
</html>
/app.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
function run() {
ReactDOM.render(<App />, document.getElementById('app'));
}
const loadedStates = ['complete', 'loaded', 'interactive'];
if (loadedStates.includes(document.readyState) && document.body) {
run();
} else {
window.addEventListener('DOMContentLoaded', run, false);
}
(IE9+)
Note: Having <script async src="..."></script> in the header ensures that the browser will start downloading JavaScript bundle before HTML content is loaded.
Source: React Starter Kit, isomorphic-style-loader

the ready function can be used like this:
$(document).ready(function () {
React.render(<App />, document.body);
});
If you don't want to use jQuery, you can use the onload function:
<body onload="initReact()">...</body>

just a wild guess, how about adding to index.html the following:
type="javascript"
like this:
<script type="javascript" src="public/bundle.js"> </script>
For me it worked! :-)

I ran into the same error. It turned out to be caused by a simple typo after changing my code from:
document.getElementById('root')
to
document.querySelector('root')
Notice the missing '#'
It should have been
document.querySelector('#root')
Just posting in case it helps anyone else solve this error.

Yes, basically what you done is right, except you forget that JavaScript is sync in many cases, so you running the code before your DOM gets loaded, there are few ways to solve this:
1) Check to see if DOM fully loaded, then do whatever you want, you can listen to DOMContentLoaded for example:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
</script>
2) Very common way is adding the script tag to the bottom of your document (after body tag):
<html>
<head>
</head>
<body>
</body>
<script src="/bundle.js"></script>
</html>
3) Using window.onload, which gets fired when the entire page loaded(img, etc)
window.addEventListener("load", function() {
console.log("Everything is loaded");
});
4) Using document.onload, which gets fired when the DOM is ready:
document.addEventListener("load", function() {
console.log("DOM is ready");
});
There are even more options to check if DOM is ready, but the short answer is DO NOT run any script before you make sure your DOM is ready in every cases...
JavaScript is working along with DOM elements and if they are not available, will return null, could break the whole application... so always make sure you are fully ready to run your JavaScript before you do...

If you use webpack for rendering your react and use HtmlWebpackPlugin in your react,this plugin builds its blank index.html by itself and injects js file in it,so it does not contain div element,as HtmlWebpackPlugin docs you can build your own index.html and give its address to this plugin,
in my webpack.config.js
plugins: [
new HtmlWebpackPlugin({
title: 'dev',
template: 'dist/index.html'
})
],
and this is my index.html file
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="shortcut icon" href="">
<meta name="viewport" content="width=device-width">
<title>Epos report</title>
</head>
<body>
<div id="app"></div>
<script src="./bundle.js"></script>
</body>
</html>

In my case this error was caused by hot reloading, while introducing new classes. In that stage of the project, use normal watchers to compile your code.

For those using ReactJS.Net and getting this error after a publish:
Check the properties of your .jsx files and make sure Build Action is set to Content. Those set to None will not be published. I came upon this solution from this SO answer.

I ran into similar/same error message. In my case, I did not have the target DOM node which is to render the ReactJS component defined. Ensure the HTML target node is well defined with appropriate "id" or "name", along with other HTML attributes (suitable for your design need)

When you got:
Error: Uncaught Error: Target container is not a DOM element.
You can use DOMContentLoaded event or move your <script ...></script> tag in the bottom of your body.
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.
document.addEventListener("DOMContentLoaded", function(event) {
ReactDOM.render(<App />, document.getElementById('root'));
})

it's easy just make basic HTML CSS js and render the script from js
mport React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
var destination = document.querySelector('#container');
ReactDOM.render(
<div>
<p> hello world</p>
</div>, destination
);
body{
text-align: center;
background-color: aqua;
padding: 50px;
border-color: aqua;
font-family: sans-serif;
}
#container{
display: flex;
justify-content: flex;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<title> app </title>
</head>
<body>
<div id="container">
</div>
</body>
</html>

In my case of using jQuery - for some reason the window.onload doesn't act the same as jQuery's onload
So this one worked for me:
<script>
$(function () { <= replacing window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
...
window.ui = ui;
});
</script>

In my case, everything in the html file was set correctly (i.e. script was at the bottom of the body tag). The problem was solved by moving the definition of a component to a separate file from where the component was rendered to the ReactDOM.
So originally I had
import React from 'react';
import ReactDOM from 'react-dom';
class Comp extends React.Component {
// component definition
}
ReactDOM.render(
<Comp />,
document.getElementById('root')
);
Problem was solved after I moved the component definition to a separate file and imported
import React from 'react';
import ReactDOM from 'react-dom';
import Comp from './CompFile';
ReactDOM.render(
<Comp />,
document.getElementById('root')
);

For my case I did mistake something below in index.js and corrected.
Error:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Solution: document.getElementById("root")
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root") // declared
);

With webpack. there is a choice to load the html file with the htmlPlugin instead of us needing to define it. When this is the case, Webpack is going to create an html file that has the script tag over above the root-div element. One quick fix would be to add a new div to the dom dynamically and then write your react dom to it. This can be done on your reactDom render function defined (usually) on the index.js file as below.
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(
<Router>
<App />
</Router>,
document.body.appendChild(document.createElement("div"))
);

Related

How to get another component on ReactJs use ES6 modules

i need help for integrate frontend ReactJS on my site. currently i avoid to use nodeJS or NPM for implement my reactJS. but i'm using ReactJS CDN. so i not run npm start when develop the reactJS. i just want to use the frontend.
Hope this will understand from the start. so i have a question, how do i able to get another component and place it on single file.
I Created file App.js. I plan that this file will become a centralize for other components.
let me share what i'm doing right now.
here is my file structure
this is my code on index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Buynow Project</title>
<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>
<script type="text/babel" src="buynow/index.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
this is my code on index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js'
ReactDOM.render(<App />, document.getElementById('root'));
this is my code on App.js
import React from 'react';
import Navbar from './components/Navbar.js'
function App(props){
return (
<div>
<Navbar/>
Hello App
</div>
);
}
export default App;
this is my code on Navbar.js
import React from 'react';
function NavBar(props) {
return (
<div>
<Navbar/>
Hi NavBar
</div>
);
}
export default NavBar;
but i got this error, and pointed on file index.js line:1
Uncaught ReferenceError: require is not defined
this is error
I confuse how to solve this. I start with the simple code just for testing if it can work or not.
please help.
https://reactjs.org/docs/react-without-jsx.html
JSX is not a requirement for using React. Using React without JSX is
especially convenient when you don’t want to set up compilation in
your build environment.
So you can't use JSX/TSX directly in your browser (need compilation). Also, you can't use import outside a module (so basically now, you can already use your function components by adding the import of all your files in the index.html).
In my experience I suggest that you use the benefits of JSX / TSX and compile your code with NPM to be more comfortable (everything is way more intuitive with jsx).
In any case, in the link that I have included, you will find how to do the equivalent of JSX with pure javascript. That's what you need. (as you can see in my small snippet)
If you want keep using react from CDN and without compiling, your code, should be something like this:
// For the Snippet i have all of your js here
// But you could just import in your index.html every separate component file you have (without any import/export syntax)
function NavBar(props) {
return React.createElement('span', null,props.title);
}
function App(props){
return React.createElement('span', null, React.createElement(NavBar, {title: 'Header'}, null),
React.createElement('span', null,'Hello App'));
}
ReactDOM.render(React.createElement(App, {}, null), document.getElementById('root'));
<html>
<head>
<meta charset="UTF-8" />
<title>Buynow Project</title>
<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>
</head>
<body>
<div id="root"></div>
</body>
</html>
Anyway, as you see, the code is not so readable this way...
EDIT
I made the same snippet on stackblitz with separated files
https://stackblitz.com/edit/web-platform-4ruju9?file=index.html
Ps. Also, don't put NavBar inside NavBar or you'll get a render loop
You have to enable module support in script tag
<script type="text/babel" data-type="module" src="./index.js"></script>
Remove React import statements as they can be directly used.

ReactDom not rendering React Elements to DOM

I am attempting to build a React app with a Django backend. However React is not rendering any elements to the html page. For some reason my index.js file is not connecting with my index.html file and grabbing the root div element by id. I created my react app with npx-create-react-app. The elements were rendering in the beginning, however I am incorporating google maps API into my project and after I did that React stopped rendering elements to the DOM. I have been stuck on these for about 2 days and I am at a lost. I have read through similar stack overflow questions and haven't been able to find an answer, Help is greatly appreciated. Here is my code:
Index.js:
'''
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App/App';
import reportWebVitals from './reportWebVitals';
import CHICHEN_ITZA from './Monuments/Chichen_Itza/Chichen_Itza'
// window.RenderCall=function(id){
// ReactDOM.render(
// <React.StrictMode>
// <App />
// <h1>This is in Index.js</h1>
// <CHICHEN_ITZA/>
// </React.StrictMode>,
// document.getElementById(id)
// );
// };
ReactDOM.render(
<React.StrictMode>
<App />
<h1>This is in Index.js</h1>
<CHICHEN_ITZA/>
</React.StrictMode>,
document.getElementById('root')
);
as you can see from commented out code I attemtpted to call the ReactDom render method from a script tag as a function from my html.index and that failed. Here is my html.index:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
</head>
<body>
<!-- <script src="../src/index.js"></script> -->
<div id="root"></div>
<H1>THIS IS ON THE INDEX.HTML</H1>
<!-- <script src="index.js">
RenderCall('root_id');
</script> -->
</body>
</html>
The H1 element, in the body of the html renders, but nothing from my index.js renders onto the html div. I tried changing the id of 'root' too and that didn't work. I imagine it has something to do with bundle or babel.
I also attempted to include my index.js as a script on my index.html page but that didn't work. I have the google api in a .env file in the directory containing my react project. The api key is accessed by a class component within the src directory. I don't know if that is relevant but I thought I would include it just in case.
here are the errors I am getting in the console when I open up the developer console:
Unchecked runtime.lastError: The message port closed before a response was received.
MapContainer.js:29 Uncaught TypeError: Cannot read properties of undefined (reading 'MAPS_API_KEY')
at Module../src/MapContainer/MapContainer.js (MapContainer.js:29:1)
at Module.options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:24:1)
at fn (hot module replacement:61:1)
at Module../src/App/App.js (bundle.js:18:84)
at Module.options.factory (react refresh:6:1)
at __webpack_require__ (bootstrap:24:1)
at fn (hot module replacement:61:1)
at Module../src/index.js (Chichen_Itza.js:21:1)
at Module.options.factory (react refresh:6:1)
Here is my MapContainer.js file:
import React, { Component } from 'react';
import { Map, GoogleApiWrapper } from 'google-maps-react';
const mapStyles ={
width: '100%',
height: '100%'
};
export class MapContainer extends Component {
render() {
return (
<Map
google = {this.props.google}
zoom = {14}
style = {mapStyles}
initialCenter={
{
lat: -1.2884,
lng: 36.8233
}
}
/>
);
}
}
export default GoogleApiWrapper({
apiKey: ProcessingInstruction.env.MAPS_API_KEY
})(MapContainer)
Unchecked runtime.lastError... This error message is telling you React is not rendering because you have a runtime error in MapContainer.js line 29:
That is apiKey: ProcessingInstruction.env.MAPS_API_KEY.
Did you mean proccess.env.MAPS_API_KEY?

Integrating React app into a Wicket/wro4j app [duplicate]

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

React is failing to render simple Hello World in MVC project

I got starting ASP.NET MVC project with the following resources added:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<script src="~/Scripts/require.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<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>
#RenderSection("scripts", required: false)
Section scripts in Index.cshtml:
<div id="root"></div>
#section scripts
{
<script src="~/Scripts/ReactJS/Index.js" type="text/babel"></script>
}
And the file itself:
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
The result is empty page with no errors.
I do not want to use Node.js, I do not want to use even require.js and babel.js, but it seems I have to.
What are the minimal dependencies of reactjs to work properly?
First, ensure ReactJS core files & Remarkable.js referenced properly as this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/[version]/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/[version]/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/[version]/remarkable.min.js"></script>
(more info: ReactJS MVC / ReactJS Core MVC)
Then, add JSX file in either <head> tag or Scripts section:
#section Scripts {
<script src="~/Scripts/ReactJS/Index.jsx"></script>
}
Assume in your <body> tag has this div container to bind...
<div id="root"></div>
Then, in JSX file the React script should be looks like this:
// Index.jsx
var Root = React.createClass({
render: function () {
return (
<h1>Hello, world!</h1>
);
}
});
ReactDOM.render(<Root />, document.getElementById('root'));
As the tutorial page said, BabelJS required if you want to use ES6 features such as arrow functions & concise methods, or use bundling mechanism (BabelBundle instead of plain ScriptBundle) to load JSX file.
Related issue:
ReactJS.NET MVC tutorial doesn't work?
Please use div before h1
var Root = React.createClass({
render: function () {
return (<div>
<h1>Hello, world!</h1> </div>);
}
});

React component rendering on server-side, but client-side does not take over

I have an EJS view which is served up to a client:
index.ejs
<!DOCTYPE html>
<html>
<head>
<title>Example app</title>
</head>
<body>
<div id="reactApp">
<%- reactContent %>
</div>
</body>
<script src="__res__/client/main.bundle.js" />
</html>
main.bundle.js is the bundle that I create using browserify:
gulpfile.js (partial)
function bundle(filename) {
var bundler = browserify('./app/client/' + filename + '.js');
bundler.transform(babelify);
bundler.transform(reactify);
return bundler.bundle()
.pipe(source(filename + '.bundle.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest('./dist/client'));
}
And the client is ultimately served this code:
main.js (bundled into main.bundle.js)
import React from 'react';
import {Login} from './auth/login.react';
React.render(React.createElement(Login), document.getElementById('reactApp'));
alert('hi');
However, even though the browser requests and recieves the main.bundle.js script, the client does not run the alert('hi'); line, which leads me to believe that the React.render line does not work either. I can affirm that Javascript is enabled, and my browser is the latest version of Chrome. My react component (Login) is as follows:
login.react.js
import React from 'react';
export class Login extends React.Component
{
handleClick() {
alert('Hello!');
}
render() {
console.log('rendered');
return (
<button onClick={this.handleClick}>This is a React component</button>
);
}
}
So, very simple. However, none of the alerts that you see in the code is ever run. The console.log('rendered'); line is never run on the server, but when I check the source code for my page, I get:
HTML output of my page
<!DOCTYPE html>
<html>
<head>
<title>Example app</title>
</head>
<body>
<div id="reactApp">
<button data-reactid=".2fqdv331erk" data-react-checksum="436409093">Lel fuck u</button>
</div>
</body>
<script src="__res__/client/main.bundle.js" />
</html>
Which means that the server correctly renders my react component, but why does the client script not work? The handleClick function never runs, my console.log lines never run, and neither does the alert lines. What is happening? The reactid and checksum are rendered correctly, shouldn't it be working? Shouldn't the React code on the client-side be smart enough to find the component and run correctly?
In your index.ejs, adding a closing element to your script tag should fix the issue: <script src="__res__/client/main.bundle.js"></script>
On a separate note, in my testing, I was getting an error in login.react.js when loading the page until I added default to the export line: export default class Login extends React.Component. Not sure if you will need to do the same.

Categories

Resources