ReactJS code compiled successfully , but not printing on Browser - javascript

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>
);
}
}

Related

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

React component error: expected a string or a class/function but got undefined

I am getting the following error in a create-react-app. Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
The app is currently a super-basic - it just imports and renders one single component:
import './App.css';
import { PasswordInput } from 'gg-react-test-lib';
function App() {
return (
<div className="App">
<PasswordInput />
</div>
);
}
export default App;
I am therefore assuming that the problem is with my component library that I am importing the PasswordInput component from. I am installing it from NPM.
It has an index.js file like:
import Radio from './Radio/Radio';
export { PasswordInput, Radio }```
Those component files themselves do a default export at the bottom of the file e.g.:
`export default PasswordInput;`
I have a pretty minimal webpack.config.js file in my component library repo:
```const TerserPlugin = require('terser-webpack-plugin');
const path = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader"
}
]
},
output: {
path: path.resolve(__dirname, "dist/"),
filename: 'bundle.js'
},
optimization: {
minimizer: [new TerserPlugin()]
},
};
My package.json:
{
"name": "gg-react-test-lib",
"version": "1.0.7",
"description": "",
"main": "dist/bundle.js",
"module": "src/index.js",
"author": "",
"license": "ISC",
"dependencies": {
"clsx": "^1.0.4",
"node-sass": "^4.13.0",
"react": "^16.12.0",
"react-dom": "^16.12.0"
},
"scripts": {
"build": "webpack"
},
"devDependencies": {
"#babel/cli": "^7.7.5",
"#babel/core": "^7.7.5",
"#babel/preset-react": "^7.7.4",
"babel-loader": "^8.0.6",
"webpack": "^4.41.3",
"webpack-cli": "^3.3.10"
}
}
.babelrc file:
{
"presets": [
"#babel/preset-react"
]
}

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 }),
],
};

after add component link error: Uncaught SyntaxError: Unexpected token export

i create test react project. Add modules and my packege.json look like:
{
"name": "untitled",
"version": "0.1.0",
"private": true,
"devDependencies": {
"babel-preset-node5": "^12.0.1",
"react-scripts": "0.9.5"
},
"dependencies": {
"babel-preset-stage-0": "^6.22.0",
"history": "^4.6.1",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-native": "^0.42.3",
"react-router": "^4.0.0",
"react-router-config": "^1.0.0-beta.1",
"react-router-dom": "^4.0.0",
"react-router-native": "^4.0.0",
"webpack": "^2.2.1",
"webpack-dev-server": "^2.4.2"
},
"scripts": {
"start": "react-scripts start",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"build": "babel input.js -o compiled.js"
}
}
and webpack.config.js
var config = {
entry: './index.js',
output: {
path:'/',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', "node5", "stage-1", 'react', "stage-0"]
}
}
]
}
};
module.exports = config;
in my component i import component Link from react-router-native and after this adding react show error 'Uncaught SyntaxError: Unexpected token export' but if i delete this string project work well. it's not the only component in the module, i can add any components like Promt, Route or Router. Why it's not work with Link?
This is code where error reproduced
import React from 'react';
import { Route, Router } from 'react-router';
import { Promt } from 'react-router';
import { Link } from 'react-router-native';
import logo from '../../logo.svg';
import './App.css';
class App extends React.Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
You need to update the regular expression for the test value in your web pack config to be test: /(\.js|\.jsx)$/
Right now you are telling webpack to only run .js files through babel loader, but you aren't telling it to also run .jsx files through babel loader.

Cannot import materialize-css in React project to use Chips

I have created project by command:
create-react-app app
I am using materialize-css http://materializecss.com/ and want to use Chips http://materializecss.com/chips.html.
import React, { Component } from 'react';
import $ from 'jquery';
import 'materialize-css';
class Form extends Component {
constructor(props) {
super(props);
$(document).ready(function() {
$('.chips').material_chip({
data: [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}],
});
});
}
render() {
return (
<div>
<div className="chips"></div>
<button>Add</button>
</div>
)
}
}
I have tried to import:
import 'materialize-css/bin/materialize.css'
import 'materialize-css/bin/materialize.js'
But it's not working. The browser throw error:
Uncaught TypeError: $(...).material_chip is not a function
Try this in your entry JS file
import 'materialize-css'; // It installs the JS asset only
import 'materialize-css/dist/css/materialize.min.css';
and you are done!
Update:
I have put all the necessary details to get your code working. Try this out
index.jsx file is here
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import 'materialize-css';
import 'materialize-css/dist/css/materialize.min.css';
class Form extends Component {
constructor(props) {
super(props);
$(document).ready(function() {
$('.chips').material_chip({
data: [{
tag: 'Apple',
}, {
tag: 'Microsoft',
}, {
tag: 'Google',
}],
});
});
}
render() {
return (
<div>
<div className="chips"></div>
<button>Add</button>
</div>
)
}
}
ReactDOM.render(<Form />, document.getElementById('app'));
and package.json is like
"dependencies": {
"babel-preset-react": "^6.16.0",
"css-loader": "^0.26.1",
"font-loader": "^0.1.2",
"jquery": "^3.1.1",
"materialize-css": "^0.97.8",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"redux": "3.6.0",
"style-loader": "^0.13.1"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.21.0",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.18.0",
"webpack": "^1.14.0",
"webpack-dev-server": "^1.16.2",
"webpack-hot-middleware": "^2.15.0"
}
and webpack.config.js is
const webpack = require('webpack');
module.exports = {
entry: [Screenshot from 2017-01-15 18-11-16
"./src/index.jsx",
"webpack-dev-server/client?http://localhost:3000/",
"webpack/hot/only-dev-server"
],
output: {
filename: "bundle.js",
path: __dirname + '/public'
},
devServer: {
contentBase: './public',
port: 3000
},
// Bundle lookup dir for included/imported modules
// By default, bundler/webpack with search here for the scripts
resolve: {
modulesDirectories: ['node_modules', 'src'],
extensions: ['', '.js', '.jsx']
},
// make sure you added babel-loader to the package
// npm i babel-loader babel-core babel-preset-es2015 -D
module: {
loaders: [
{
test: /\.js[x]?$/, // Allowing .jsx file to be transpiled by babel
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
},
{ test: /\.css$/, loaders: [
'style',
'css?importLoaders=1',
'font?format[]=truetype&format[]=woff&format[]=embedded-opentype'
] },
{ test: /\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader: 'file-loader?name=fonts/[name].[ext]' }
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
No error whatsoever.
With NPM:
Step 1: Install materialize
If you are using npm, make sure you install materialize using the command listed in their documentation:
npm install materialize-css#next
DON'T MISS the '#next' at the end. The installed version will be something like: "^1.0.0-rc.2" OR "^1.0.0-alpha.4"
Step 2: Import materialize:
import 'materialize-css/dist/css/materialize.min.css'
import M from 'materialize-css/dist/js/materialize.min.js'
OR
import 'materialize-css/dist/css/materialize.min.css'
import M from 'materialize-css'
In order for the css import to work, you would need a css loader. Note that this loader is already included in projects built using create-react-app so you don't need the next steps. If instead, you are using custom webpack config, then run:
npm install --save-dev style-loader css-loader
Now add css-loader and style-loader in webpack config
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.join(__dirname, "build")
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "react"]
}
}
}
]
}
}
Now you can initialize components individually, or all at once using M.AutoInit();
With CDN:
Add the following in your HTML file.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
Then, in the webpack config, add externals: https://webpack.js.org/configuration/externals/

Categories