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
Related
My app works perfectly in local, without errors, but when I try to deploy it on netlify or github pages, when I open it, the page is blank and many errors are displayed in the console.
The error says
TypeError: can't access property "length", e is undefined
where e corresponds to items (which is a state).
If I remove these lines of code, I get another error that always concerns items: the problem this time is with items.some, where items is null again.
Whatever I try to do items always result null.
I tried console.log(items) in many component files and in all of them the result is null.
This is the netlify link where you can see the error:
https://celadon-otter-917b4e.netlify.app/
Navbar.js, where the error is located:
import { Link } from 'react-router-dom';
import Searchbar from './Searchbar';
import { useContext } from 'react';
import FavoritesContext from '../FavoritesContext';
function Navbar() {
const { items } = useContext(FavoritesContext);
return (
<div className='navbar'>
<Link to={'/'} style={{ textDecoration: 'none' }}>
<div className='logo-container'>
<img src="/foglia.png" alt="logo" className='logo'/>
<h3>just<span>vegetables</span></h3>
</div>
</Link>
<Searchbar />
<Link to={'/favorites/'} style={{ textDecoration: 'none' }}>
<h4 className='favor'>Favorites: <span>{items.length}</span></h4>
</Link>
</div>
)
}
export default Navbar;
FavoriteContext.js:
import React, { createContext, useState, useEffect } from "react";
const FavoritesContext = createContext();
export function FavoritesProvider({ children }) {
const [ items, setItems ] = useState([]);
useEffect(() => {
const recipesFavorites = JSON.parse(localStorage.getItem('favorites-recipes'));
setItems(recipesFavorites);
}, []);
const saveToLocalStorage = (item) => {
localStorage.setItem('favorites-recipes', JSON.stringify(item))
}
const addToFavorites = (title, image, id, favorite) => {
if (!favorite) {
const newFavoriteList = [...items, { title, image, id }]
setItems(newFavoriteList);
saveToLocalStorage(newFavoriteList);
};
};
const removeFromFavorites = (title, image, id, favorite) => {
if (favorite) {
const newFavoriteList = items.filter((fav) => fav.id !== id);
setItems(newFavoriteList);
saveToLocalStorage(newFavoriteList);
};
};
return (
<FavoritesContext.Provider value={{ items, setItems, addToFavorites, removeFromFavorites }}>
{children}
</FavoritesContext.Provider>
)
}
export default FavoritesContext;
Card.js:
import { Link } from 'react-router-dom';
import FavoritesContext from '../FavoritesContext';
function Card({ title, image, id }) {
const { addToFavorites } = useContext(FavoritesContext);
const { removeFromFavorites } = useContext(FavoritesContext);
const { items } = useContext(FavoritesContext);
const checkIsAdd = () => {
if(items.some((val) => val.id === id)) {
return true;
}};
const [favorite, setFavorite] = useState(checkIsAdd);
const isInFavorites = (id) => {
return (
<img src='../cuore-pieno.png' alt="like" className='favorite blue' onClick={() => {removeFromFavorites(title, image, id, favorite); toggle()}}/>
)
}
const toggle = () => {
isInFavorites(id);
setFavorite(!favorite);
}
return (
<div className='card'>
{!favorite ? <img src='../cuore-vuoto.png' alt="like" className='favorite' onClick={() => {addToFavorites(title, image, id, favorite); toggle()}}/> : isInFavorites(id)}
<Link to={'/recipe/' + id}>
<img src={image} alt='' className='card-image'/>
<div className='card-info-cnt'>
<p className='card-title'>{title}</p>
</div>
</Link>
</div>
)
}
export default Card;
package.json
{
"name": "projetto-react",
"version": "0.1.0",
"homepage": "https://michela-z.github.io/justVegetables",
"main": "index.js",
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.3.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"lodash": "^4.17.21",
"node-env-webpack-plugin": "^1.1.0",
"process": "^0.11.10",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-icons": "^4.4.0",
"react-router-dom": "^6.3.0",
"react-scripts": "^5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d dist",
"serve": "webpack-dev-server --mode development --open --hot",
"start": "webpack-dev-server",
"build": "webpack --mode production",
"test": "react-scripts test",
"eject": "react-scripts eject",
"webpack": "webpack",
"webpack-dev-server": "webpack-dev-server",
"dev": "npm run webpack-dev-server -- --env mode=development",
"prod": "npm run webpack -- --env mode=production"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.18.13",
"#babel/preset-env": "^7.18.10",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^8.2.5",
"css-loader": "^6.7.1",
"file-loader": "^6.2.0",
"gh-pages": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"source-map-loader": "^4.0.0",
"url-loader": "^4.1.1",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.10.0"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const port = process.env.PORT || 3000;
module.exports = {
mode: 'development',
entry: {
index: {
import: './src/index.js',
dependOn: 'shared',
},
another: {
import: './src/another-module.js',
dependOn: 'shared',
},
shared: 'lodash',
},
output: {
filename: '[name].bundle.js',
path: path.join(__dirname, '/dist')
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
}
}
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource'
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
new webpack.ProvidePlugin({
process: 'process/browser',
}),
],
devServer: {
host: 'localhost',
port: port,
historyApiFallback: true,
open: true
},
optimization: {
runtimeChunk: 'single',
},
};
I'm new to programming, this is my first react app, I tried everything that was in my ability.
Check if there item present before checking its length {items.length}
you can achieve this by
{item && item.length} or
{items?.length}
this will get rid of the errors displayed in live deploy
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"
}
}
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>
);
}
}
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
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 }),
],
};