ReactDom.render not rendering the html content - reactjs

I am able to transpile the jsx code but in browser its not loading anything. I am using babel and webpack too.
app.jsx
const ReactDom = require('react-dom');
const React = require('react');
ReactDOM.render(
<h1>Hello World</h1>,
document.getElementById("root")
);
index.html
<html>
<head>
</head>
<body>
<div id="root"></div>
<script type="text/javascript" src="./js/bundle.js">
</script>
</body>
</html>
webpack.config.js
module.exports = {
entry: './jsx/app.jsx',
output: {
path: __dirname + '/js/',
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
loaders: ['babel-loader']
}
]
}
}
bundle.js
------
------
(function(module, exports, __webpack_require__) {
const ReactDom = __webpack_require__(15);
const React = __webpack_require__(4);
ReactDOM.render(React.createElement(
'h1',
{ htmlFor: 'yes' },
'Hello World'
), document.getElementById("root"));
}),
------
------
When I looked into html page source it showing linked to bundle.js in script tag but page is blank.
You can check my complete project on Github complete code
Steps I am following to run
npm run build
static (I am using node-static)
then loading index.html in browser but page is blank.

You have a typo - ReactDOM should be ReactDom. The error that is shown in the console is Uncaught ReferenceError: ReactDOM is not defined.

Related

React element is not rendering / React Setup Issue

I am trying to learn to react, after spending two days on setting up webpack and babel. Finally, I am trying to run some sample code. I am trying to print some strings from my react element, and unable to get this element working.
I do get the "Hello World" which is from the HTML, and no compilation errors for react, so I can validate client-server setup is working well.
However, the react element is not rendered.
Following is three file setup.
components/homepage.js
"use strict";
var React = require('react');
var Home = React.createClass({
render: function () {
return (
<div className="jumbotron">
<h1>PluralSight Adminstrator</h1>
<p>React, React Router, and Flux for ultra responsive website</p>
</div>
);
}
});
module.exports = Home;
And index.js
const jquery = $ = require('jquery');
const Home = require('./components/homepage');
const ReactDOM = require('react-dom');
ReactDOM.render(<Home/>, document.getElementById('app'));
And index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="index.js"></script>
</head>
<body>
<div id="app"></div>
Hello World.:)
</body>
</html>
webpack.config.dev.js
const webpack = require('webpack');
const path = require('path');
module.exports = {
debug: true,
devtool: 'inline-source-map',
noInfo: false,
entry: [
'eventsource-polyfill', // necessary for hot reloading with IE
'webpack-hot-middleware/client?reload=true', //note that it reloads the page if hot module reloading fails.
path.resolve(__dirname, 'src/index')
],
target: 'web',
output: {
path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`.
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: path.resolve(__dirname, 'src')
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
{test: /(\.css)$/, loaders: ['style', 'css']},
{test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
{test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000'},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'}
]
}
};
The following code should work (replace the home component code):
var Home = class Home extends React.Component {
render() {
return (
<div className="jumbotron">
<h1>PluralSight Adminstrator</h1>
<p>React, React Router, and Flux for ultra responsive website</p>
</div>
);
}
}
According to docs, if you want to use create-react-class then you need to install the package using NPM and require it as shown below:
var createReactClass = require('create-react-class');
The compiler might not show the error, but your browser's console must be showing some error.
Ref fiddle: https://jsfiddle.net/69z2wepo/194263/

Do you have to include .jsx in script tags in your html?

I see code online for a very simple react app like this:
index.html:
<!doctype html>
<html>
<head>
...
</head>
<body>
<div id="root"></div>
</body>
</html>
And then index.jsx:
import "babel-polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
But how does the index.jsx javascript file even get run if there is no script tag in the index.html? Something similar to this: <script type="text/babel" src="./index.jsx">?
Expanding on my comment, this is an example of a webpack configuration you might use. This will auto generate an index.html file inside dist folder with the index_bundle.js embedded. HtmlWebpackPlugin has options you can pass, but as I said, this is a basic example.
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackConfig = {
entry: 'index.jsx',
output: {
path: 'dist',
filename: 'index_bundle.js'
},
module: {
loaders: {
test: /.jsx?$/,
loader: ['babel-loader'],
exclude: path.join(__dirname, 'node_modules'),
}
},
plugins: [new HtmlWebpackPlugin()]
};
Packages you'll need:
npm install --save-dev webpack babel-loader html-webpack-plugin
To use run webpack.
EDIT
You will also need a .babelrc file. Basic example:
{
"presets": {
"es5"
}
}

ReactJs AdminLTE Dashboard

I am new in ReactJS. I want to use ReactJS-AdminLTE in my project. Can anybody tell how to use it with step by step process.
Steps I followed
1) I set Reactjs environment using https://www.tutorialspoint.com/reactjs/ tutorial
2) Then I install ReactJS-AdminLTE using command npm install adminlte-reactjs
My webpack.config file is
var path=require('path');
var config = {
entry: './main.js',
output: {
path: path.join(__dirname, "./"),
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
App.jsx
import React from 'react';
import reactjsAdminlte from 'adminlte-reactjs';
class App extends React.Component {
render() {
return (
<Box
width = 3
border = true
content = 'The body of the box'
theme = 'box-primary'
title = 'Collapsable'
collapsed = true
boxTools = ['collapse']
/>
);
}
}
export default App;
Index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = "index.js"></script>
</body>
</html>
But result is not displaing.
Are you using ReactDOM to render your app component to the HTML?
import ReactDOM from 'react-dom';
ReactDOM.render(
<App />,
document.getElementById('app')
);

ReactDOM does not render component into html

Just started redux, get stuck on a weird situation, webpack shows no error, but in the html, the component did not get rendered. The file structure:
dist
bundle.js
node_modules
src
index.js
.babelrc
index.html
package.json
server.js
webpack.config.js
index.html
<html>
<head>
<title>jie blog</title>
<meta charset="utf-8">
</head>
<body>
<div id="root"></div>
</body>
<script src="dist/bundle.js">
</script>
</html>
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { Router, Route, Redirect, browserHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
class App extends React.Component{
render(){
return(
<div>
hello world
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('root')
)
server.js
var http = require('http')
var express = require('express')
var httpProxy = require('http-proxy')
var fs = require('fs')
var babelrc = fs.readFileSync('./.babelrc')
var config = JSON.parse(babelrc)
require('babel-core/register')(config)
var proxy = httpProxy.createProxyServer({})
var app = express()
app.use(require('morgan')('short'))
// webpack
var webpack = require('webpack')
var config = require('./webpack.config')
var compiler = webpack(config)
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}))
app.use(require('webpack-hot-middleware')(compiler))
app.all(/^\/api\/(.*)/, function api(req, res){
proxy.web(req, res, {
target: 'http://localhost:5000'
})
})
app.get(/.*/, function root(req, res){
res.sendFile(__dirname + '/index.html')
})
const server = http.createServer(app)
server.listen(process.env.PORT || 3000, function(){
const address = server.address()
console.log('listening on %j', address)
})
webpack.config.js
const webpack = require('webpack')
const path = require('path')
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client',
path.resolve(__dirname, 'src/index.js')
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
extensions: ['', '.jsx', '.js', '.json', '.scss']
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
}
}
output html
<body>
<div id="root"></div>
<script src="dist/bundle.js">
</script>
</body>
It looks it's not an issue with ReactDOM but instead a configuration problem.
In server.js
...
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath // <--- /static/
}))
...
publicPath specifies the public URL address of your bundle.js when referenced in a browser. So /static/bundle.js as you set in your webpack.config.js. Ok fine !
So Index.html need to request for /static/bundle.js. and NOT dist/bundle.js
...
<script src="static/bundle.js"></script>
...
Check output.publicPath configurations for webpack for more informations
As index.html requested for your bundle at /dist and webpack-dev-middleware handle requests at /static, an index.html file was returned instead of a your bundle.js
app.get(/.*/, function root(req, res){
res.sendFile(__dirname + '/index.html')
})
It's why you got Uncaught SyntaxError: Unexpected token < bundler.js:1.
The problem is that Babel is transpiling only .jsx files:
test: /\.jsx?$/,
while your file with JSX has a .js extension (index.js)

Webpack React library to global variable in window

I use webpack to build React components.
Here is the JSX file:
// index.js
var React = require('react');
var ReactDOM = require('react-dom');
var renderHelloComponnet = function(id) {
ReactDOM.render(
<h1>Hello, World!</h1>,
document.getElementById(id)
);
}
Then, I want to call the function renderHelloComponnet in html
I have the config file for webpack:
module.exports = {
entry: {
index: './src/index.js'
},
output: {
path: __dirname + '/build',
filename: '[name].bundle.js',
libraryTarget: "var",
library: ["ABC"],
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: { presets:['react'] }
}
]
}
}
However I can't render my component in html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script type="text/javascript" src="./build/index.bundle.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/javascript">
ABC.renderHelloComponnet('example');
</script>
</body>
</html>
I get the error: TypeError: ABC.renderHelloComponnet is not a function
What you export in your module.exports is what you get in your library var. So if in your index.js you export renderHelloComponent:
module.exports = renderHelloComponent;
then in your ABC var you'll get the function:
<script type="text/javascript">
ABC('example');
</script>
If you want your library var to actually have the renderHelloComponent method you can export an object with this function inside:
module.exports = {
renderHelloComponent: renderHelloComponent
}
Then you will be able to do this:
<script>
ABC.renderHelloComponent('example');
</script>

Resources