Embedded react component not rendered/loaded in html page. (webpack/babel) - javascript

I am trying to set up my first Webpack Babel React project.
Although the html code shows on various browsers (http://localhost:80), the embedded react component is not loaded. The following message can be read in the console
"Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
at invariant (transformed.js:304)"
Click here to see error image
Find below the different config and code files setting up this environment.
./app/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first local App</title>
</head>
<body>
<div id='app'> </div>
<h1> Testing </h1>
</body>
</html>
./app/index.js
var React = require('react');
var ReactDOM = require('react-dom');
var App = require('../components/App');
ReactDOM.render(
<App />,
document.getElementById('app')
);
./components/App.js
import React from 'react';
import ReactDOM from 'react-dom';
export class App extends React.Component {
constructor(){
super();
console.log('Component has been constructed ')
}
render() {
return (
<div>
<h1>This is a simple test</h1>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
package.json
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"deploy":"npm run build && npm run git-commit && npm run git-push",
"build": "webpack",
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^2.30.1",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
}
}
.babelrc
{presets:["react"]}
webpack.config
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin ({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: __dirname + '/app/index.js' ,
module: {loaders: [ {test:/\.js$/, exclude:/node_modules/, loader:'babel-loader' } ]},
output: {filename: 'transformed.js', path: __dirname + '/build'},
plugins: [HTMLWebpackPluginConfig],
resolve : { extensions: [".js", ".jsx"] }
};
Thanks,
Sebastian

Looks like you have
ReactDOM.render(
<App />,
document.getElementById('app')
);
in there twice. Could be other errors as well, but remove it from App.js and see if that helps.

At first, remove second render in <App />, at second, change var App = require('../components/App'); to import {App} from '../components/App'; And your error must gone.

Related

Issue running React App on Django server with webpack

I am building a web-application using Django as the backend and want to implement a ReactJS framework frontend. Each application that I have as of now runs properly, independently of one another. I have also implemented webpack and it appears to configure properly, as it will run my ReactJS application on the localhost. Being new to webpack (and web-development in general) I am unsure how to get React to run on the Django local server (127.0.0.1:8000). I understand from the many forums I've read through that the javascript files need to be bundled and then read into the django app. Below are the relevant files:
package.json
{
"name": "package.json",
"version": "1.0.0",
"description": "This is the private repository for the USA Baseball analytics team.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "SET NODE_ENV=development babel src -d lib",
"build-prod": "SET NODE_ENV=development babel src -d lib",
"start": "webpack-dev-server"
},
"repository": {
"type": "git",
"url": "git+https://github.com/USAB-Analytics/BaldEagle.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/USAB-Analytics/BaldEagle/issues"
},
"homepage": "https://github.com/USAB-Analytics/BaldEagle#readme",
"dependencies": {
"react": "^16.2.0",
"express": "^4.16.3",
"react-dom": "^16.4.1",
"react-sortable-hoc": "^0.8.3",
"yarn": "^1.7.0",
"react-prop-types": "^0.4.0",
"semantic-ui-react": "^0.77.1",
"react-router-dom": "^4.2.2"
},
"devDependencies": {
"babel": "^6.23.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-stage-1": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "3.0.4",
"style-loader": "^0.19.1",
"css-loader": "^0.28.10",
"jsx-loader": "^0.13.2",
"react": "^16.4.0",
"webpack": "^4.10.2",
"webpack-bundle-tracker": "^0.3.0",
"webpack-cli": "^3.0.4",
"webpack-command": "^0.2.1",
"webpack-dev-server": "^3.1.4"
},
"keywords": []
}
webpack.config.js
var path = require("path");
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
//var BundleTracker = require('webpack-bundle-tracker')
const port = process.env.PORT || 3000;
process.env.NODE_ENV = 'production';
module.exports = {
mode: 'development',
entry: './frontend/src/index.js',
output: {
filename: 'bundle.[hash].js'
},
devtool: 'inline-source-map',
module: {
rules: [
// First Rule
{
test: /\.(js)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
// Second Rule
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: true,
camelCase: true,
sourceMap: true
}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'Custom template',
template: './webapp/templates/webapp/home.html',
})
],
devServer: {
host: 'localhost',
port: port,
historyApiFallback: true,
open: true
}
};
frontend/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './css/main.css';
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import {HomePage} from './components/HomePage.js'
import {Bios} from './components/Bios.js'
import {Bio} from './components/Bio.js'
import {NavBar} from './components/NavBar.js'
import {TeamsList} from './components/TeamsList.js'
import {TOSBios} from './components/TOSBios.js'
import {NT18Bios} from './components/NT18Bios.js'
import {CNTBios} from './components/CNTBios.js'
import {NT15Bios} from './components/NT15Bios.js'
class App extends React.Component {
render(){
var styles = {
'marginLeft': '210px'
}
return (
<Router>
<div className="col-sm-10">
<NavBar />
<div style={styles}>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/bios/:id" component={Bio} />
<Route path="/bios/" component={Bios} />
<Route path="/teams/tos/:id" component={Bio} />
<Route path="/teams/cnt/:id" component={Bio} />
<Route path="/teams/nt18/:id" component={Bio} />
<Route path="/teams/nt15/:id" component={Bio} />
<Route path="/teams/cnt/" component={CNTBios} />
<Route path="/teams/nt18/" component={NT18Bios} />
<Route path="/teams/nt15/" component={NT15Bios} />
<Route path="/teams/tos/" component={TOSBios} />
<Route path="/teams/" component={TeamsList} />
</Switch>
</div>
</div>
</Router>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
webapp/templates/webapp/home.html
<!-- {% extends "webapp/header.html" %} -->
{% load render_bundle from webpack_loader %}
<html>
<head>
<meta charset="UTF-8">
<title>React with Django</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
These shouldn't be running on the same server. If you are looking to connect them you should be able to create config files and say if production the url I hit is xx.com/users otherwise if it is development it is localhost:8000/users. Why would you need both to run on the same server?
We use django-webpack-loader to render our webpack bundles in a django template (for a Vue app but it's the same fundamental idea).
You've configured your webpack for development mode. It means that you run the webpack development server. But you need to build your front-end application into a bundle and then use this bundle for your server side. Just remove the devServer section. Also, you can erase this process.env.NODE_ENV = 'production'; and change the mode to production. This operation will set your process.env.NODE_ENV to production(https://webpack.js.org/concepts/mode/).
If you need to test your app in development mode you can add proxy to package.json with the address of your back-end and run front and back separately.
Solution:
Add an npm command:
"build:prod": "<your_build_command> && mv <output_path>/index.html <path_to_backend>/<app_name>/templates && mv <output_path>/* <path_to_backend>/static"
Add this to your Django app settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

React index.html rendered but react component does not

i couldn't figure out why ReactDOM does't render my simple component but seems to keep and render just the plain index.html
package.json
{
"name": "client2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "babel-node buildScripts/server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.3",
"path": "^0.12.7"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.8.3",
"webpack-dev-middleware": "^3.1.3"
},
"babel": {
"presets": [
"es2015",
"react"
],
"env": {
"presets": [
"react-hmre"
]
}
}
}
webpack.config.dev.js
import webpack from 'webpack'
import path from 'path'
const HtmlWebpackPlugin = require('html-webpack-plugin');
export default {
devtool: 'inline-source-map',
entry: [
path.resolve(__dirname, 'src/index.js')
],
output: {
path: path.resolve(__dirname, 'src'),
publicPath: '/',
filename: 'bundle.js'
},
module:{
rules:[
{test: /\.js$/ , loader:'babel-loader', exclude: '/node_modules/'},
{test: /\.jsx$/ , loader:'babel-loader', exclude: '/node_modules/'}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body'
})
]
}
buildScript/server.js
import express from 'express';
import path from 'path';
import webpack from 'webpack';
import config from '../webpack.config.dev';
const compiler = webpack(config);
/* var express = require('express')
var path = require('path') */
const port = 8081;
const app = express();
app.listen(port, function (error) {
if(error) {
console.log(error);
}
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, '../src/index.html'));
});
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(){
super();
console.log("App Hello")
}
render(){
return(
<div>
<h1>Howdy from React!</h1>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hey!</title>
</head>
<body>
<div id="root"></div>
<h1>Hello World!</h1>
</body>
</html>
The only response i get is
With no logs from my index.js react "App".
I've been trying several solutions, none happened aside from my express server not working. What might be the problem here ? Thank you very much !
As I wrote in comment, you should include your js
<html lang="en">
<head>
<title>Hey!</title>
</head>
<body>
<div id="root"></div>
<h1>Hello World!</h1>
<script src="/bundle.js"></script>
</body>
</html>
Your html file needs to link to bundle.js
<script src="/bundle.js"></script>
Thanks for Leo Odishvili and Ben West for helping above - the answer is really adding <script src="/bundle.js"></script> to the index.html
The only change was to
change /bundles.js to "./webservice_entrypoint/bundle.js"as webservice_entrypoint would be the url path to my react app.
Thanks everyone !
Also you can check the "html-webpack-plugin" and add the plugin to the "plugins" configuration of the webpack.config.js, this will allow you to use any template html file from inside your src directly and bundle it in the dist/ folder with the included script tag already compiled and added. It is really an useful plugin.

Deploying react app with webpack server

I am a beginner in ReactJS and was just exploring it and trying to configure it with Webpack and Babel when I experienced an error when I run the application using npm start.
Following are some of files:-
package.json
{
"name": "reactstarter",
"version": "1.0.0",
"description": "A basic React application to explore its state and beauty",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"keywords": [
"reactjs"
],
"author": "user1705",
"license": "MIT",
"dependencies": {
"debug-log": "^1.0.1",
"react": "^15.3.2",
"react-dom": "^15.3.2"
},
"devDependencies": {
"webpack": "^1.13.2"
}
}
There are two directories src directory and dist directory inside the root folder.
File: src/index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = "/app/bundle.js"></script>
</body>
</html>
File:- src/app/App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
export default App;
File:- src/app/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
And webpack.config.js:-
var webpack= require(webpack);
var path= require(path);
var DIST_DIR=path.resolve(__dirname,"dist");
var SRC_DIR= path.resolve(__dirname,"src");
var config={
entry:SRC_DIR+"/app/index.js",
output:{
path:DIST_DIR+"/app",
fileName:bundle.js,
publicPath:"/app/",
},
devServer: {
inline: true,
port: 7777
},
modules:{
loaders:[
{
test:/\.js?/,
include:SRC_DIR,
loader:"babel-loader",
query:{
presets:["react","es2015","stage-2"]
}
}
]
}
};
module.exports=config;
So now whenever I run the command npm start,it gives the following error:-
Being a beginner I have no idea as what is the issue?? If anyone has come across this similar issue or knows about the error,please contribute your knowledge and show me the right path.
change
output:{
path:DIST_DIR+"/app",
fileName:bundle.js,
publicPath:"/app/",
},
to
output:{
path:DIST_DIR+"/app",
fileName:"bundle.js",
publicPath:"/app/",
},
It seems that you forgot the quotes when you were requiring the npm modules:
var webpack= require('webpack');
var path= require('path');

Facing some issues with ReactJS first program

I just started learning ReactJS, I am following this tutorials here.
egghead.io I just completed its first video and developed an app as shown in video, But some how I can see the html part but failed to load the dynamic content coming from the App.js Below is my code:
App.js
import React from 'react';
class App extends React.Component {
// always expected to return
render() {
return '<div><h4>Hello World of ReactJS</h4></div>'
}
}
export default App;
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ReactJS Tutorial</title>
</head>
<body>
<h1>ReactJS First Project</h1>
<div id="app">
</div>
<script src="index.js"></script>
</body>
</html>
main.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render('<App/>' , document.getElementById('app'));
package.json
{
"name": "App",
"version": "1.0.0",
"description": "First application of ReactJS",
"private": true,
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "AD",
"license": "Apache",
"dependencies": {
"babel-core": "^6.13.1",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.13.1",
"babel-preset-react": "^6.11.1",
"react": "^15.3.0",
"react-dom": "^15.3.0"
},
"devDependencies": {
"webpack-dev-server": "^1.9.0"
}
}
webpack.config.js:
module.exports = {
entry: "./main.js",
output: {
path: "./",
fileName: "index.js"
},
devServer: {
inline: true,
port: 3333
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
Would need some help to run it, not sure. I have installed everything as asked in the video, I am using node 6.2.2.
In your main.js, change:
ReactDOM.render('<App/>' , document.getElementById('app'));
to
ReactDOM.render(<App/>, document.getElementById('app'));
The quotes are the problem. You want to render your imported component, not some String. Also I would be interested if you got a warning in the console.

After deploying [react-router] "did not match any routes"

I´m currently developing a React-Redux Appliaction using Webpack & npm.
While development I run "start": "node server.js" (from my package.json) and my app is then reachable on localhost:3000/myApp.
But I would like to make this App available to other users. I have a linux server running apache, where some of my previously jQuery Apps are running that work fine.
However, to bundle my React App I run "production": "webpack -p" and the output of this is /dist/bundle.js. Afterwards, I created a html file, included the bundle.js on put both on the server
<!DOCTYPE html>
<html>
<head>
<title>Urlaub-planer</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--<link rel="stylesheet" href="./Urlaubspalner/css/daterangepicker.css" type="text/css">-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
<!-- Auth0Lock script -->
<script src="//cdn.auth0.com/js/lock-9.0.min.js"></script>
</head>
<body>
<div class="todoapp" id="root"></div>
<script src="./bundle.js"></script>
</body>
</html>
When trying to access I got the following error:
browser.js?26d3:49Warning: [react-router] Location "/test/index.html" did not match any routes
This is the File where my Routes are defined
import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import {Router, Route, IndexRoute, browserHistory} from 'react-router'
import createLogger from 'redux-logger'
import App from './containers/App'
import VacationSummary from './containers/vacation/VacationSummary'
import VacationRequest from './containers/vacation/VacationRequest'
import VacationRequestSummary from './containers/vacation/VacationRequestSummary'
import Home from './containers/Home'
import Demo from './components/Demo'
import rootReducer from './reducers/reducers'
import thunkMiddleware from 'redux-thunk'
var injectTapEventPlugin = require("react-tap-event-plugin");
injectTapEventPlugin();
const logger = createLogger();
let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, logger) (createStore)
let store = createStoreWithMiddleware(rootReducer)
let rootElement = document.getElementById('root')
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('./reducers', () => {
const nextRootReducer = require('./reducers').default
store.replaceReducer(nextRootReducer)
})
}
render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="Home" component={Home}/>
<Route path="VacationSummary" component={VacationSummary}/>
<Route path="VacationRequest" component={VacationRequest}/>
<Route path="VacationRequestSummary" component= {VacationRequestSummary}/>
</Route>
</Router>
</Provider>,
rootElement
)
I have found several Questions on SO with a similar purpose, but they are mostly having problems, when running this with the webpack-dev-server.
I want it as I said on my traditional apache server.
What do I have to do, to make this work outside of my development Environment?
Sorry if that Q is to basic, but it is my first project using all this new npm, webpack, node ... stuff and so on.
Finally my package.json
{
"name": "Urlaubsplaner",
"version": "0.0.1",
"main": "index.js",
"scripts": {
"server": "node server/server.js",
"start": "node server.js",
"watch": "webpack --watch",
"production": "webpack -p"
},
"author": "Auth0",
"license": "MIT",
"dependencies": {
"classnames": "^2.2.5",
"css-loader": "^0.23.1",
"material-ui": "^0.15.2",
"moment": "^2.13.0",
"react": "^15.1.0",
"react-bootstrap-daterangepicker": "^3.1.0",
"react-dom": "*",
"react-redux": "*",
"react-router": "*",
"react-tabs": "^0.7.0",
"react-tap-event-plugin": "^1.0.0",
"react-yearly-calendar": "^1.1.4",
"redux": "*",
"redux-form": "^5.2.5",
"redux-logger": "^2.6.1",
"redux-thunk": "*",
"style-loader": "^0.13.1"
},
"devDependencies": {
"babel-core": "^5.6.18",
"babel-loader": "^5.1.4",
"babel-plugin-react-transform": "^1.1.0",
"express": "^4.13.3",
"webpack": "^1.9.11",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.2.0"
}
}
And my webpack.config
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" },
{test: /\.js$/,
loaders: [ 'babel' ],
exclude: /node_modules/,
include: __dirname
}]
}
}
Greetings.
According to your current react router paths following links would work:-
/
/VacationSummary
/VacationRequest
/VacationRequestSummary
I cannot find /test/home.html route anywhere in your react-router. So it would throw error for sure. Also you dont need to specific .html in the end for links.
Also I would suggest you to make your /Home Index Route instead of Route.
Now are you localhost:3000/myApp this working, because it should not as myApp is not there in your router urls.
So you home page(or index.html) should be accessible at localhost:3000 from the code you have shared above.

Categories

Resources