No Error so is why my component not rendering? - reactjs

I am brand spanking new to this React stuff and stumbling around trying to understand all of the moving parts. I have started a server with the webpack dev server and attempting to render my code to http://localhost:8080/ but to no avail. It's just a simple form component. There are more than likely many things wrong with how I have things set up, but again, still learning! Thanks for any help anyone can offer. I have an index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Practicing Components</title>
</head>
<body>
<div id="app"></div>
<script type='text/babel'></script>
</body>
</html>
This index.html file is rendering my main.js file:
import React from 'react';
import ReactDOM from 'react-dom';
class Main extends React.Component {
render() {
return (
<div>
<h1>Welcome to the Name Board!</h1>
<Form />
<Button />
</div>
);
}
}
class Form extends React.Component {
constructor(props) {
super(props);
this.state= {value: 'Please type your name.'};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
render() {
return (
<input type="text" value={this.state.value} onChange={this.handleChange} />
);
}
}
class Button extends React.Component {
render() {
return (
<button value="Submit">
</button>
);
}
}
ReactDOM.render(<Main />, document.getElementById('app'));
I've set up my module loaders and entry point and all that in my webpack.config.js:
var path = require("path");
module.exports = {
entry: {
app: ["./main.js"]
},
output: {
path: path.resolve(__dirname, "build"),
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['react', 'es2015']
}
}
]
}
};
However, despite not having any error messages and my server being successfully connected, I am rendering nothing.

Looks like you're not even loading the bundle:
<script src="/build/bundle.js"></script>

It's not React. It's the HTML code. It doesn't seem to be telling the browser to load the bundle from anywhere, e.g. the <script> tag doesn't have an attribute src="/build/bundle.js".
So maybe to fix it, you'd have better luck after changing your HTML code to look like so?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Practicing Components</title>
</head>
<body>
<div id="app"></div>
<!-- See how "src" is now set to "app.bundle.js"? -->
<script src='/build/bundle.js'></script>
</body>
</html>

Related

Webpack Not Serving React Component

I have created my webpack config file below:
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/main.js',
output: {
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: '/node_modules/',
use: [
{
loader: 'babel-loader'
}
]
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: {minimize: true}
}
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: './src/index.html',
filename: './index.html'
})
]
};
and added all the necessary packages babel with env and react presets. I have my index.html file and TestComponent like below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React 16 Webpack Setup</title>
</head>
<body>
<script src="bundle.js" type="text/javascript"></script>
<div id="test">
</div>
</body>
</html>
and component code:
import React, { Component } from 'react';
export default class TestComponent extends Component {
render(){
return (
<div>
<h2>React Setup</h2>
</div>
)
}
}
Here's my main.js file where I'm hosting the component:
import React from "react";
import ReactDOM from "react-dom";
import Test from './TestComponent';
ReactDOM.render(<Test/>, document.getElementById("test"));
The problem is that when I run this script from package.json, I don't get any output/dist folder and also the component doesn't render in the browser. On which url do I have to visit to see the output just like with create-react-app?
Import your <script> at the bottom of the <body> tag in the HTML.
In your case, the browser is reading through the DOM and finding the <script> tag before it is finding the <div id="text"> node. What this means is that the browser will read through your script, and then try and render your <Test/> component into an HTML node with the id="test". The browser can't find the HTML node with the id="test" though because it hasn't read it yet, so it fails.
Make sense? See below...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React 16 Webpack Setup</title>
</head>
<body>
<div id="test"></div>
{* import scripts at the bottom of the body *}
<script src="bundle.js" type="text/javascript"></script>
</body>
</html>
Hope this helps, let me know if you're still running into issues.

Webpack/React app setup failing - "React is not defined"

I am using webpack to set up a React app.
When I serve my app locally using webpack-dev-server I get VM1086 bundle.js:9812 Uncaught ReferenceError: React is not defined in the console.
I have know idea what is going on as there aren't any other errors or information to go on, as webpack seems to compile ok.
index.html
<html>
<head>
<script src="./dist/bundle.js" ></script>
</head>
<body>
<div id="mount"></div>
</body>
</html>
webpack config
var path = require('path');
module.exports = {
entry: [
'./src/App.js',
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: ['node_modules'],
loader: 'babel-loader',
query: {
babelrc: true,
},
}
]
}
}
app.js
import React from 'react';
import ReactDOM from 'react-dom';
console.log('Hello World!');
class App extends React.Component {
render() {
return (<div>314159263</div>);
}
}
ReactDOM.render(<App />, document.getElementById('mount'))
try to define bundle.js after <div id="mount"></div> because may be your bundle compiles your code and it does not find where to render the code
</head>
<body>
<div id="mount"></div>
<script src="./dist/bundle.js" ></script>
</body>
</html>
and also in your webpack add this
query: {
presets: ['es2015', 'react']
}

React + Webpack: React.createElement: type should not be null, undefined, boolean, or number

Why am I getting that error in the console of the chrome ?
My code:
index.html
<!DOCTYPE html>
<html>
<head>
<title>hello React</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="root">
<!-- my app renders here -->
</div>
<script src="../react-15.3.1/build/react.js"></script>
<script src="../react-15.3.1/build/react-dom.js"></script>
<script src="./dist/bundle.js"></script>
</body>
</html>
main.js
import SalutaMondo from './salutamondo';
var UnaProva = React.createClass({
render: function(){
return (
<div>
<SalutaMondo/>
<div>Ciao Emiliano</div>
</div>
);
},
});
ReactDOM.render(<UnaProva />, document.getElementById("root"));
salutamondo.js
var SalutaMondo = React.createClass({
render: function(){
return (
<h1>Hello World</h1>
);
}
});
module.export = SalutaMondo;
webpack.config.js
const webpack = require('webpack')
const path = require('path')
module.exports = {
entry: [ './src/salutamondo.js', './src/main.js' ],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
}
]
}
}
In your webpack config, you're using the babel-loader. This implies that you're using ES6 style modules. In salutamondo.js, you're using CommonJS style modules. As a result, the babel-loader isn't picking up the module. Can you try:
export default SalutaMondo;
instead of:
module.export = SalutaMondo;
This is likely due to salutamondo.js using CommonJS module format, while main.js is using ECMAScript module. I recommend keeping everything in ECMAScript modules:
var SalutaMondo = React.createClass({
render: function(){
return (
<h1>Hello World</h1>
);
}
});
export default SalutaMondo;

Uncaught SyntaxError: embedded: Unexpected token var Comment = React.createClass({...});

Hey great folks of Stack Overflow. I am learning REACTJS right now. And it's throwing this error: Uncaught SyntaxError: embedded: Unexpected token var Comment = React.createClass({...});
Here's my code: `
<body>
<div id="example">
</div>
<div id="container">
</div>
<script type="text/babel">
var Comment = React.createClass({...});
var Board = React.createClass({
getinitialState: function(){
return{
comments: [
"I like bacon.",
"Want to get ice cream?",
"Okay, we've got enough comments now."
]
}
},
render: function() {
return(
<div className="board">
{
this.state.comments.map(function(text, i){
return(<Comment key={i}>{text}</Comment>);
})
}
</div>
);
}
})
ReactDOM.render(<Board/>, document.getElementById("container"));
</script>
<script src="https://npmcdn.com/react#15.3.0/dist/react.min.js"></script>
<script src="https://npmcdn.com/react-dom#15.3.0/dist/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script> <!-- older transpiler 5.8.24 works with this app-->
</body>
`
I am not sure what's going on here. I'm trying to create a component via var Comment which should have an array which is "var Comment = React.createClass({..}); I don't know why it's not recognizing it as an array that would be used. I would definitely appreciate some help on this, good folks of StackOverflow.
You are writing your React code in JSX which is not understood by the script tag. In order to run the React code either use the webpack or browserify to bundle your jsx into a .js file and then include that .js file in the script tag or in order to test your code use the JSFIDDLE to write your code . It has integration for JSX.
Sample webpack.config.js
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'src');
var APP_DIR = path.resolve(__dirname, 'src');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
}
};
module.exports = config;
index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
var Board = React.createClass({
getinitialState: function(){
return{
comments: [
"I like bacon.",
"Want to get ice cream?",
"Okay, we've got enough comments now."
]
}
},
render: function() {
return(
<div className="board">
{
this.state.comments.map(function(text, i){
return(<Comment key={i}>{text}</Comment>);
})
}
</div>
);
}
})
ReactDOM.render(<Board/>, document.getElementById("container"));
index.html
<body>
<div id="example">
</div>
<div id="container">
</div>
<script src="./src/bundle.js"></script>
</body>
You also need to have a package.json to provide all the dependencies.
Here is a good video tutorial series that can help you with all the configuration
JSX syntax is not understood by the script tag. The JSX needs to be compiled to JavaScript. Try out your example in JSFiddle. JSFiddle has integration scripts to work with React.
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js">
</script>
You can try moving your JSX code to a new .jsx file and referencing that file in your .html
I met the same problem with you, seems we were watching the same tutorial video :)
Anyway, getinitialState should be getInitialState. Watch out the 4th letter.
Do the one change in your snippet codes which it is given in above section.
Correct minor spelling mistake here.
getinitialState() should be getInitialState().
ES5 use getInitialState() to initialize the state variables i.e React.createClass(..).
ES6 use constructor() to initialized the state variables i.e class Comment extends React.Component(..)
Here is another example of ES6, please check out this.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
</head>
<body>
<div id="content"></div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js'></script>
<script type="text/babel">
class CommentBox extends React.Component{
constructor(props){
super(props);
this.state = {
editable : false,
commentMsg : ">>"
};
}
save(event){
this.setState({commentMsg:event.target.value})
}
remove(){
this.setState({
editable:false
})
}
edit(){
this.setState({
editable:true
})
}
renderForm(){
return (
<div className="row">
<div>{this.props.children}</div>
<div><textArea name="commentBox" onChange={this.save.bind(this)}></textArea></div>
<button type="button" className="btn btn-danger">Save</button>
<button type="button" className="btn btn-success" onClick={this.remove.bind(this)}>Remove</button>
{this.state.commentMsg}
</div>
);
}
renderHtml(){
return (
<div className="row">
<div>{this.props.children}</div>
<div>{this.state.commentMsg}</div>
<button type="button" className="btn btn-danger" onClick={this.edit.bind(this)}>Edit</button>
<button type="button" className="btn btn-success" onClick={this.remove.bind(this)}>Remove</button>
</div>
);
}
render() {
if(this.state.editable){
return this.renderForm(this);
}else{
return this.renderHtml(this);
}
}
}
class Board extends React.Component{
constructor(props){
super(props);
this.state ={
comments:[
'Techical Comments',
'Wordpress Comments',
'Facebook Comments'
]
}
}
render(){
return(
<div className="container-fluid">{
this.state.comments.map(function(text,i){
return (
<CommentBox key={i}>{text}</CommentBox>
);
})
}
</div>
);
}
}
ReactDOM.render(
<Board />
, document.getElementById('content'))
</script>
</body>
</html>

How to use react-intl v2 + webpack to load locale file?

I have a setup to use webpack to manage all my assets. it works fine. Now I plan to use react-intl version 2 to support multiple languages.
I have managed to make components defined in package 'react-intl' work,
import {IntlProvider, FormattedNumber, FormattedPlural} from 'react-intl';
class App extends Component {
constructor(props) {
super(props);
this.state = {
name : 'Eric',
unreadCount: 1000,
};
}
render() {
const {name, unreadCount} = this.state;
return (
<p>
Hello <b>{name}</b>, you have {' '}
<FormattedNumber value={unreadCount} /> {' '}
<FormattedPlural value={unreadCount}
one="message"
other="messages"
/>.
</p>
);
}
}
But I can't figure out what's the correct way to load locale file through webpack and refer them in component. Since the package has breaking upgrade recently, there is no much documentation about it either. the wiki page is empty for now
https://github.com/yahoo/react-intl/wiki
I wonder What's the correct way to do this?
xiopang,
I just wrote a webpack plugin based around the translations example from react-intl v2. Hopefully it works for you: https://gist.github.com/marr/95f7a8a3f5529e7e668048548198b9eb
the webpack config plugins then look like:
new TranslateWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'index.hbs', // Load a custom template
inject: 'body', // Inject all scripts into the body
chunks: [ 'app' ],
app: true
}),
and index.hbs:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
window.App = <%= htmlWebpackPlugin.options.app %>
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>

Resources