Event handling is not working in a fresh react project - javascript

I've been trying my first steps with react.js and after playing around a bit (installing Bootstrap, adding some loaders for LESS & Co.) at some point the event handlers (onSubmit, onChange) stopped working. At first, I thought I just messed up my code.
However, when I copy the example for a controlled components form into a freshly initialized npm project with React 17.0.2, these handlers are still not working as expected. E.g. the onSubmit handler:
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
Neither does the alert show, nor is the default event handling prevented. The page simply reloads when I hit the submit button.
For example, if I put an alert into the constructor it is being shown.
Here is the full package.json
{
"name": "app-retry",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"start": "webpack-dev-server --open",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
},
"devDependencies": {
"#babel/core": "^7.16.12",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"babel-loader": "^8.2.3",
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.67.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.3"
}
}
and here is the full webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: path.resolve(__dirname, 'src', 'index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
dev: {
hot: true,
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
// attach the presets to the loader (most projects use .babelrc file instead)
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}
]
},
plugins: [new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'src', 'index.html') })]
};
The index.js is
import React from "react";
import ReactDOM from "react-dom";
// lines as copied from the react example
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
and finally the index.html template
<html>
<head>
<title>Hello world App</title>
</head>
<body>
<div id="root"></div>
<script src="./bundle.js"></script>
</body>
</html>
What am I doing wrong? Is the example code wrong or is there a flaw in my setup?

Related

React application crashing in chrome - Error code: Out of Memory

Trying to launch my very first React application, and when I try to launch it using "dev" script in package.json, then it crashes the chrome tab. In task manager ram consumption gets even to 7.5 GB
My code is:
src\index.jsx
import * as React from "react";
import * as ReactDOM from "react-dom";
import {Header} from "./header";
window.addEventListener('load', ()=>{
ReactDOM.render(<Header />, document.getElementById('react_root'));
})
src\header.jsx
import * as React from "react";
export function Header(){
return (
<Header>
<h1>Reddit for our own</h1>
</Header>
);
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Testing</title>
</head>
<body>
<div id="react_root"></div>
</body>
</html>
package.json
{
"name": "skillbox",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build:dev": "env NODE_ENV=development webpack --config webpack.config.js",
"build:prod": "env NODE_ENV=production webpack --config webpack.config.js",
"dev": "env NODE_ENV=development webpack-dev-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"ts-loader": "^9.4.2",
"typescript": "^4.9.5",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"webpack-dev-server": "^4.11.1"
},
"dependencies": {
"html-webpack-plugin": "^5.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
webpack.config.js
const path = require('path');
const NODE_ENV = process.env.NODE_ENV;
const HTMLWebpackPlugin = require('html-webpack-plugin');
const IS_DEV = NODE_ENV === "developement";
module.exports = {
resolve:{
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json']
},
mode: NODE_ENV ? NODE_ENV : 'development',
entry: path.resolve(__dirname, 'src/index.jsx'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js'
},
module:{
rules: [{
test: /\.[tj]sx$/,
use: ['ts-loader']
}]
},
plugins: [
new HTMLWebpackPlugin({ template: path.resolve(__dirname, 'index.html') })
],
devServer:{
port: 8000,
open: true,
hot: false
}
};
Console does not give any error, it is just the browser, which crashes because of memory.

ERROR in ./src/index.js Module build failed (from ./node_modules/babel-loader/lib/index.js):

I'm trying to set up ReactJs from scratch but npm start, dev, build, and watch are throwing the error below:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\da4na4\web\stocker\src\index.js: Unexpected character '�' (1:0)
I have setup package.json, webpack.config.js, and .babelrc configurations. I have equally tried out previous answers on Stack Overflow, yet the issue persist. Below are the configurations of the respective files:
package.json
{
"name": "stocker",
"version": "1.0.0",
"description": "A product inventory web app to help you keep track of your stocks and meet demands",
"main": "webpack.config.js",
"scripts": {
"test": "jest ./src/tests",
"dev": "webpack --mode development",
"build": "webpack --mode production",
"watch": "webpack --watch",
"start": "webpack serve --mode development --open --hot"
},
"keywords": [
"products",
"Inventory"
],
"author": "Emmanuel Joshua",
"license": "MIT",
"devDependencies": {
"#babel/core": "^7.12.16",
"#babel/preset-env": "^7.12.16",
"#babel/preset-react": "^7.12.13",
"#webpack-cli/serve": "^1.3.0",
"babel-loader": "^8.2.2",
"css-loader": "^5.0.2",
"html-loader": "^1.3.2",
"html-webpack-plugin": "^5.0.0",
"jest": "^26.6.3",
"jsdom": "^16.4.0",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0",
"webpack": "^5.21.2",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"react": "^17.0.1",
"react-dom": "^17.0.1"
}
}
webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const htmlPlugin = new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "index.html"
});
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "public"),
filename: "js/app.min.bundle.js",
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(scss|css)$/, use: ["sass-loader", "css-loader", "style-loader"]
},
{
test: /\.(html)$/, use: ["html-loader"]
}
],
},
plugins: [htmlPlugin],
target:"node",
devServer:{
port: 3000,
contentBase: path.resolve(__dirname, "public")
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
};
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
These are the index.js and the App.js files
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './js/App';
ReactDOM.render(
<App firstname={"Joshua"} />,
document.getElementById("root")
)
js/App.js
import React, {Component} from 'react';
class App extends Component{
constructor(props){
super(props);
}
render(){
return(
<h1>Hello {this.props.firstname}, Welcome to our Website!</h1>
)
}
}
export default App;
This tripped me a while. I found out one of the reasons is because of the directory naming path.
I used # for a folder name and it gave me the same error you're reading into.
e.g. my path
C:/Users/johndoes/codes/# wip/project1/sub/
My suggestion is looking at the pathing and seeing if everything is on the right place and referred to correctly.

Webpack 4 basic React js hello world fails with "Module parse failed: Unexpected token"

Update:
Code pushed to https://github.com/gsouvik/react_spa_experiment
Initial Post:
I know there are hundreds of threads out there, some had typos in webpack config, some used the loaders in a wrong way, some got it solved, some still open. But after numerous tries I still cannot get this working, a simple "Hello World" using Webpack 4, React js.
What I did
I was following this video tutorial line by line:
React & Webpack 4 from scratch
My package.json
{
"name": "my_react_experiment_2",
"version": "1.0.0",
"description": "Basic react with webpack ",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server --mode development --hot",
"build": "webpack --mode production"
},
"author": "Souvik Ghosh",
"license": "ISC",
"dependencies": {
"react": "^16.4.2",
"react-dom": "^16.4.2"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
}
My webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.export = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/build'),
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/templates/index.html'
})
]
};
My .babelrc
{
"presets": ["env", "react"]
}
My directory structure
Expected behaviour
I fire up the dev server npm run dev. Expected to see my shiny new React js page saying "My first React Webpack project" (from the component /components/App.js)
Actual Behavior
ERROR in ./src/index.js 5:16
Module parse failed: Unexpected token (5:16)
You may need an appropriate loader to handle this file type.
| import App from "./components/App";
|
ReactDOM.render(, document.getElementById('root'));
| //ReactDOM.render('Hello User ', document.getElementById('root'));
# multi (webpack)-dev-server/client?http://localhost:8080 (webpack)/hot/dev-server.js ./src main2
If required I can share the codebase via a git repo. Any help is greatly appreciated.
The issue is with typo in your webpack config file.
You have module.export which is not correct. It should be module.exports
Working example
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/build'),
filename: 'index_bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/templates/index.html'
})
]
};

Webpack Module build failed when importing React components

I'm working on a project to integrate React and ASP.Net together. I've made the initial Hello World and every works as expected (not hard :p). I'm using webpack with babel-loader to generate my `bundle.js.
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render(<h1>LPMU</h1>, document.getElementById('root'))
This is my webpack.config.js file:
module.exports = {
context: __dirname,
entry: "./App.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
watch: true,
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['babel-preset-env', 'babel-preset-react']
}
}
}
]
}
}
After this worked out, I tried to add my App.js component and all other components into my react folder, inside Scripts on my ASP.NET project. I'm not doing the export default App since I'm using the ReactDOM.render(). I import my components into my App.js as usual:
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import './App.css';
import Header from './Header';
import Footer from './Footer';
import Landing from './Landing';
import * as lpmuGlobal from './lpmu-global';
And then I just render the App component:
ReactDOM.render(<App />, document.getElementById('root'))
Now when I run npm run webpack again, I get 2 problems, which are the following:
size name module status
704 B 0 ./App.js built failed ✖
Δt 596ms (1 asset hidden)
./App.js
0:0 error Module build failed (from ./node_modules/babel-loader/lib/index.js):
configuration
0:0 warning The 'mode' option has not been set, webpack will fallback to
'production' for this value. Set 'mode' option to 'development' or
'production' to enable defaults for each environment.
✖ 2 problems (1 error, 1 warning)
I've been searching for a solution, but since I'm really new to webpack, I don't know what happens, if I need anything else on my webpack.config.js, if I have to import my components in any other way or whatever.
ALso this is my json.package:
{
"name": "lpmu-react-app",
"version": "1.0.0",
"description": "Integración de ReactJS con ASP.NET",
"main": "App.js",
"scripts": {
"start": "react-scripts start",
"webpack": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "DPS",
"license": "ISC",
"dependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0",
"webpack-command": "^0.2.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.4"
}
}
Thanks
The error is because you have not added a .babelrc file or babel options to your package.json file to provide babel options.
In order to enable the preset you have to define it in your .babelrc
file
Add babel option to your package.json as such :
package.json:
{
"name": "lpmu-react-app",
"version": "1.0.0",
"description": "Integración de ReactJS con ASP.NET",
"main": "App.js",
"scripts": {
"start": "react-scripts start",
"webpack": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
"babel":{
"presets": ["env","react"]
}
"author": "DPS",
"license": "ISC",
"dependencies": {
"react": "^16.4.0",
"react-dom": "^16.4.0",
"webpack-command": "^0.2.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.4"
}
}
Go through the below links for further clarification:
https://babeljs.io/docs/en/babelrc.html
https://babeljs.io/en/setup/#installation
About the warning :
Webpack 4 needs you to include the mode option to your configuration, as you would usually want to have development and production configurations separate.
Go through the link below which explains in detail how to set configurations.
https://www.valentinog.com/blog/webpack-4-tutorial/
module.exports = {
context: __dirname,
entry: "./App.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
watch: true,
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['babel-preset-env', 'babel-preset-react']
}
}
}
]
}
}
Hope that helps :)

Webpack and Reactjs app not loading html

I'm trying to build an app with reactjs+webpack+babel. My webpack.config.js is:
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'src/client/bin');
var APP_DIR = path.resolve(__dirname, 'src/client/app');
var config = {
context: APP_DIR,
entry: {
vendor: ['react', 'react-dom'],
app: APP_DIR + '/index.jsx'
},
resolve: {
extensions: [".webpack.js", ".web.js", ".js", ".jsx"]
},
output: {
path: BUILD_DIR,
filename: '[name].js'
},
devServer: {
inline:true,
port: 9000
},
module : {
loaders : [
{
test : /\.jsx?/,
exclude: /node_modules/,
include : APP_DIR,
loader : 'babel-loader',
query: {
presets: ['react', 'es2015']
}
}
]
}
};
module.exports = config;
Then my index.jsx is:
import React from 'react';
import {render} from 'react-dom';
class App extends React.Component {
render () {
return <p> Hello React!</p>;
}
}
render(<App/>, document.getElementById('app'));
And my html file:
<html>
<head>
<meta charset="utf-8">
<title>React.js using NPM, Babel6 and Webpack</title>
</head>
<body>
<div id="app"></div>
<script async src="bin/bundle.js" type="text/javascript"></script>
</body>
</html>
And this html is in the bin folder. What am I doing wrong, so when I open throw browser (and webpack server) I don't have that html.
EDIT:
{
"main": "index.jsx",
"scripts": {
"start": "webpack-dev-server --inline --hot",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "André Roque Nº31260",
"license": "ISC",
"dependencies": {
"react": "^0.14.9",
"react-dom": "^0.14.9",
"react-router": "^4.1.1",
"webpack": "^2.5.1"
},
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.1",
"babel-polyfill": "^6.23.0",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"html-webpack-plugin": "^2.28.0",
"webpack": "^2.5.1"
}
}
Try serving the contentBase to the devServer from the folder in which the html file is present with you bundled script. You should provide path to the webpack-dev-server such as following example:
devServer: {
contentBase: path.resolve(__dirname, 'src/client/bin'),
inline:true,
port: 9000
},
Hope this helps.

Categories