React Component not loading with Webpack and Babel Beginner's level - javascript

I am trying to understand how React, Babel and Webpack interact with each other, but I get the following error: Uncaught TypeError: Super expression must either be null or a function. The CSS is rendering just fine but the HTML isn't, though I was able to see it in the console (view image below).
Any suggestions?
package.json
{
"name": "react-raw",
"version": "1.0.0",
"description": "",
"main": "index.js",
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
},
"scripts": {
"start": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^16.8.4",
"react-dom": "^16.8.4"
},
"devDependencies": {
"#babel/core": "^7.4.0",
"#babel/preset-env": "^7.4.1",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.23.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.2.1"
}
}
index.js
var React = require("react");
var ReactDOM = require("react-dom");
require("./index.css");
class App extends React.Component() {
render() {
return <div>Hello Christian!!</div>;
}
}
ReactDOM.render(<App />, document.getElementById("app"));
webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin"); //installed via npm
//const webpack = require("webpack"); //to access built-in plugins
module.exports = {
entry: "./app/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index_bundle.js"
},
module: {
rules: [
{ test: /\.(js)$/, use: "babel-loader" },
{ test: /\.css$/, use: ["style-loader", "css-loader"] }
]
},
mode: "development",
plugins: [new HtmlWebpackPlugin({ template: "app/index.html" })]
};
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>React Raw</title>
</head>
<body>
<div id="app"></div>
</body>
</html>

Your problem is with the signature of your class component:
class App extends React.Component() {
render() {
return <div>Hello Christian!!</div>;
}
}
This is how you need to declare it:
class App extends React.Component{
render() {
return <div>Hello Christian!!</div>;
}
}
Note the extra () i omitted
You can read more about classes in here

Related

npm dev run generates huge main.js file

I have a Django application and trying to rewrite my JS frontend to React. I found some tutorial how to organize the structure of React app:
frontend/
static/frontend/main.js/main.js
src/
index.js
components/App.js
package.json
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"scripts": {
"dev": "webpack --mode development ./src/index.js --output-path ./static/frontend/main.js",
"build": "webpack --mode production ./src/index.js --output-path ./static/frontend/main.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.20.12",
"#babel/preset-env": "^7.20.2",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^9.1.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
},
"dependencies": {
"fs-promise": "^2.0.3"
}
}
webpack.config.js
module.exports = {
devtool: false,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: { presets: ['#babel/env','#babel/preset-react'] },
}
}
]
}
};
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django REST with React</title>
</head>
<body>
<h1>Anything</h1>
<div id="app">
<!-- React will load here -->
</div>
</body>
{% load static %}
<script src="{% static "frontend/main.js/main.js" %}"></script>
</html>
sample code in App.js
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
const [value, setValue] = React.useState(0);
function increment() {
setValue(value + 1);
}
return (
<div className="app">
<h1>{value}</h1>
<button onClick={increment}>+1</button>
</div>
);
}
ReactDOM.render(
<div>
<App />
</div>,
document.getElementById("root")
);
const container = document.getElementById("app");
ReactDOM.render(<App />, container);
If I got it right, any React component imported in index.js will be compiled to js code in main.js which is included to index.html. I created a simple code in App.js just to try it and it does work, but it generates a 30k lines main.js file. Is it normal? I guess it shouldn't be like this since it consumes much more resources than my 400-lines js code, so what am I doing wrong ?part of code in main.js

Browser not displaying MP4 #webpack-dev-server #React.js #JS

I started a new React.js project in Visual Studio Pro 22 without CRA.
My react component renders accurately (minus a local .mp4 file).
The .mp4 file is contained inside a video element, inside a div, within my main component.
Edge developer tools shows the video element, and the .mp4 file (bundled by webpack).
However, the .mp4 file will not play or show in the browser.
I get this error.
localhost/:1
GET http://localhost:8080/preview net::ERR_ABORTED 404 (Not Found)
Here is my webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
resolve: {
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: { react: path.join(__dirname, 'node_modules', 'react') }
},
plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })],
module: {
rules: [
{
test: /\.css/i,
use: ['style-loader', 'css-loader']
},
{
test: /\.js$/,
exclude: /node_modules/,
use:
{
loader: "babel-loader",
options:
{
presets: ['#babel/preset-env', '#babel/preset-react']
}
}
},
{
test: /\.(png|mp4)$/i,
type: "asset/resource"
},
{
test: /\.txt$/i,
type: 'asset/source'
},
{
test: /\.(woff|woff2|ttf)$/i,
type: "asset/resource"
},
{
test: /\.html$/,
use: ["html-loader"]
}
]
}
}
here is my package.json
{
"name": "tascticnodes",
"version": "0.0.0",
"description": "tascticnodes",
"main": "index.js",
"author": "",
"presets":
[
"#babel/preset-env",
"#babel/preset-react"
],
"scripts":
{
"build": "webpack --watch",
"start": "webpack serve"
},
"keywords": [],
"license": "ISC",
"devDependencies":
{
"#babel/core": "^7.16.5",
"#babel/preset-env": "^7.16.5",
"#babel/preset-react": "^7.16.5",
"babel-loader": "^8.2.3",
"css-loader": "^6.5.1",
"file-loader": "^6.2.0",
"html-loader": "^3.1.0",
"html-webpack-plugin": "^5.5.0",
"style-loader": "^3.3.1",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.6.0"
},
"dependencies":
{
"#aws-amplify/ui-react": "^2.1.5",
"aws-amplify": "^4.3.11",
"bootstrap": "^5.1.3",
"react": "^17.0.2",
"react-bootstrap": "^2.0.4",
"react-dom": "^17.0.2",
"typewriter-effect": "^2.18.2"
}
}
here is my config.babelrc
{
"presets": ["#babel/preset-env, "#babel/preset-react"]
}
here is my SRC directory
screen shot of my directory
here is my passIt.js(the standard app.js)
import React from 'react';
import Typewriter from 'typewriter-effect';
import './index.css';
import Amplify from 'aws-amplify';
import { API } from 'aws-amplify';
import { Button, Form } from 'react-bootstrap';
import preview from './preview.mp4';
import awsExports from './aws-exports';
Amplify.configure(awsExports);
async function addContact()
{
const data =
{
body:
{
name: formState.name,
email: formState.email,
message: formState.message
}
}
console.log(data);
const apiData = await API.post('formapi', '/items', data);
console.log({ apiData });
alert('Mail sent');
};
const formState = { name: '', email: '', message: '' };
function updateFormState(key, value)
{
formState[key] = value;
};
const Hello = () => {
return (
<div>
<div>
<div>
<form>
<Typewriter
onInit={(typewriter) =>
typewriter
.typeString('Welcome to Anvil')
.start()} />
</form>
<Form>
<Form.Group>
<Form.Label>Name</Form.Label>
<Form.Control placeholder="Name" onChange={e =>
updateFormState('name', e.target.value)} />
</Form.Group>
<Form.Group>
<Form.Label>Email</Form.Label>
<Form.Control placeholder="Email" onChange={e =>
updateFormState('email', e.target.value)} />
</Form.Group>
<Form.Group>
<Form.Label>Message</Form.Label>
<Form.Control placeholder="Message" onChange={e =>
updateFormState('message', e.target.value)} />
</Form.Group>
<Button onClick={addContact}>Send a message</Button>
</Form>
</div>
</div>
<video autoPlay muted loop>
<source src="preview" type="video/mp4" />
</video>
</div>
)
};
export default Hello;
here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Check my divs</title>
<link href="index.css" rel="stylesheet" type="text/css">
<link C:\Users\zack\source\repos\tascticnodes\src\preview.mp4 />
</head>
<body id="body">
<div id="root"></div>
</body>
</html>
here is my index.js
import React from 'react';
import { render } from 'react-dom';
import Hello from './passIt';
render(<Hello />, document.getElementById('root'));
Specify output file name in webpack.config.js
View the Wepback Documentation: file-loader
Here is what your loader should look like:
`
{
test: /\.(mov|mp4)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]'
}
}
]
}
`
Take a look at this thread:
Webpack 3 locates .mp4 file but video is not playable

Using React in only one part of a multi-page application

I already have a multi-page website which currently has two tools built with Node.js, Express, MongoDB, vanilla JS. Each tool has its own web page. I want to add a third tool on my website. This new tool will be built using React.
The main "App" component should have a "Top", "Body" and "Bottom" component. However, when I try to import these components into the App file, the content does not show.
App component:
import React from 'react';
import Top from './Top/Top.js';
import Body from './Body/Body.js';
import Bottom from './Bottom/Bottom.js';
class App extends React.Component {
render() {
return (
<div>
<Top />
<Body />
<Bottom />
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
Top component:
import React from 'react';
class Top extends React.Component {
render() {
return (
<div>
<div>Top goes here</div>
</div>
);
}
}
export default Top;
Body component and Bottom component are similar to Top.
When I import the components into the App, the content does not show. However, if I do not import and write all the components in one file, the content shows.
I would like to separate the components into separate files as shown above for easier readibility and navigation.
Furthermore, when I try to import the components into the main App component, I also get this error in the Chrome web developer console:
How can I separate my components into separate files and import them correctly where needed without errors?
Thanks!
Edit: this is my webpack configuration
const path = require('path');
const autoprefixer = require('autoprefixer');
module.exports = {
entry: './public/js/birdApp/birdApp.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
chunkFilename: '[id].js',
publicPath: ''
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
options: {
modules: {
localIdentName: "[name]__[local]___[hash:base64:5]",
},
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: () => [
autoprefixer({})
]
}
}
]
},
{
test: /\.(png|jpe?g|gif)$/,
loader: 'url-loader?limit=10000&name=img/[name].[ext]'
}
]
}
};
Edit2: my package.json file
"name": "rstools",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "env-cmd -f ./config/dev.env nodemon src/app.js --ext js,hbs,css"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-cli": "^6.26.0",
"babel-preset-react-app": "^3.1.2",
"body-parser": "^1.19.0",
"env-cmd": "^10.1.0",
"express": "^4.17.1",
"hbs": "^4.1.1",
"mongodb": "^3.5.7",
"mongoose": "^5.9.11",
"osrs-json-api": "^1.4.1",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"devDependencies": {
"#babel/core": "^7.10.4",
"#babel/preset-env": "^7.10.4",
"#babel/preset-react": "^7.10.4",
"autoprefixer": "^9.8.4",
"babel-loader": "^8.1.0",
"css-loader": "^3.6.0",
"html-loader": "^1.1.0",
"html-webpack-plugin": "^4.3.0",
"postcss-loader": "^3.0.0",
"style-loader": "^1.2.1",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12",
"webpack-node-externals": "^2.3.0"
}
}

ReactJS code compiled successfully , but not printing on Browser

After a lot of efforts i was able to install and configure ReactJS. After executing "npm start" command, the code was "COMPILED SUCCESSFULLY" and redirected me to the web browser.
But there wasn't any output, ie., the browser was "blank".
Can anyone resolve this?? ( my first post here )
Also check the code that i have used..
index.html file
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = 'index_bundle.js'></script>
</body>
</html>
App.js
import React, { component } from 'react';
class App extends Component {
render(){
return(
<div>
<h1> Hello World</h1>
<p>Hello </p>
</div>
);
}
}
export default App;
main.js
import React from 'react';
import { render } from 'react-dom';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App />, document.getElementById('app'));
package.json snippet
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './main.js',
output: {
path: path.join(__dirname, '/bundle'),
filename: 'index_bundle.js'
},
devServer: {
inline: true,
port: 8001
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './index.html'
})
]
}
The only issue is the output is not getting displayed on browser..
command prompt
COMMAND PROMPT AFTER "npm start"
browser
output not displaying
Add an .babelrc file in root folder with following:
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
And package.json is expected to include following dependencies:
"devDependencies": {
"#babel/core": "^7.4.0",
"#babel/preset-env": "^7.4.2",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"react": "^16.8.5",
"react-dom": "^16.8.5",
"style-loader": "^0.23.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.2.1"
}
Update
Also update webpack.config.js to:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./main.js",
output: {
path: path.join(__dirname, "/bundle"),
filename: "index_bundle.js"
},
devServer: {
inline: true,
port: 8001
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./index.html"
})
]
};
Check the path and change Component to component.
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route path="/" component={HomePage} exact />
</div>
</Router>
);
}
}

React router page rendering issue

Learning React right now tried to use react-router for page routing, but because of some reasons I always see the blank page instead of rendered component.
I'm using webpack-dev-server as dev server.
Looking for your help and advices
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="dist/css/app.css">
</head>
<body>
<div id="root"></div>
<script src="dist/js/app.js"></script>
</body>
</html>
app.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, IndexRoute, hashHistory } from "react-router";
import App from './Pages/App';
import Archives from './Pages/Archives';
import Features from './Pages/Features';
import Settings from './Pages/Settings';
const app = document.getElementById('root');
// ReactDOM.render(<Layout/>, app);
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Features}/>
<Route path='archives' component={Archives}/>
<Route path='settings' component={Settings}/>
</Route>
</Router>
, app);
App component
import React from 'react';
import { Link } from 'react-router'
export default class App extends React.Component{
render(){
return (
<div>
<h1>App</h1>
<Link to="/archives">Archives</Link>
<Link to="/settings">Settings</Link>
{this.props.children}
</div>
);
}
}
package.json
{
"name": "Planner",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"dependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"history": "^4.6.1",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-router": "^4.1.1",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.4"
},
"devDependencies": {},
"scripts": {
"dev": "webpack-dev-server --content-base --inline --hot",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
UPDATED:
Webpack config
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : null,
entry: "./js/app.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
}
]
},
output: {
path: path.resolve(__dirname, 'dist/js'),
filename: "app.js",
publicPath: '/dist/js/'
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};

Categories