Why am I a getting an error that react is undefined? - javascript

I'm new to react and I'm importing using esmodules but I keep getting an error telling react is undefined. I'm running it through babel and then bundling it with webpack. I've looked at some of the other related questions but none seem to be helping with my problem. Why is it comming up undefined and how can I fix it?
Error:
Uncaught ReferenceError: React is not defined
at Object.<anonymous> (bundle.js:formatted:76)
at n (bundle.js:formatted:11)
at bundle.js:formatted:71
at bundle.js:formatted:72
package.json:
{
"name": "reactTestProject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Brandon Lind",
"license": "MIT",
"devDependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.3.4",
"#babel/preset-env": "^7.3.4",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3"
},
"dependencies": {
"#babel/polyfill": "^7.2.5",
"react": "^16.8.4"
}
}
files:
filename: app.js
import Square from "./SquareDiv.js";
let main= document.getElementsByTagName("main")[0];
console.log("wtf")
main.appendChild(<Square/>);
filename: SquareDiv.js
import React from "react";
class Square extends React.Component{
constructor(props){
super(props);
this.state={
isOn: true
}
}
getIsOn(){
let currentState= this.state.isOn;
let pastState= state;
if(currentState===false){
currentState===true;
}
else {
currentState ===false;
}
return pastState;
}
render(){
<div onClick={getIsOn} class="square">this.state.isOn</div>
}
}
export {Square};
babel.config.js:
const presets=[
[
"#babel/preset-env",
{
targets:{
esmodules: true,
edge: 10,
chrome: 30,
safari: 30,
firefox: 30,
opera: 30
}
}
],
[
"#babel/preset-react",
{
pragma: "pragma",
pragmaFrag: "pragmaFrag",
throwIfNamespace: false
}
]
];
module.exports={
presets
};
webpack.config.js:
module.exports={
entry: "./src/app.js",
output:{
filename: "bundle.js"
},
module:{
rules:[
{ test: /\.m?js$/,
exclude: /(node_modules|browsers_components)/,
use:{
loader: "babel-loader",
options: {
presets: ["#babel/preset-env","#babel/preset-react"]
}
}
}
]
}
}

Don't use this syntax import React from "./node_modules/react";.
It will work only for files that are created in the root directory, and your components are likely in src/.
Webpack will resolve everything for you, so you can just use import React from 'react'; everywhere.
Also replace this string: export {Square}; with export default Square
And you can omit .js extension when import, so you can write it this way: import Square from "./SquareDiv";
If you don't want to use default export, you should use import {Square} from "./SquareDiv"
You can read the differences between default and regular exports here
You have a lot of problems in your code snippet. I mentioned some of them in my answer. There are more of them:
Don't use class keyword in JSX, it should be className
Use curly braces to render JS values like this.state.isOn
When you use handlers, don't use it like onClick={getIsOn}, use onClick={() => getIsOn()} and etc.
I suggest you to go through React tutorial which will save your time a lot!

App.js needs to import react. Every file that has JSX in it has to import react.
This particular error is happening because the JSX for Square in app.js is getting transpiled into a React method call, and since you haven’t imported React in app.js, React is not defined.
UPDATE
Also, this will fix a couple other errors...
Change <div onClick={getIsOn} class="square">this.state.isOn</div> to:
return <div onClick={this.getIsOn} className="square">{this.state.isOn}</div>

Related

How to use FontAwesome with Nuxt3?

I'm trying to use FontAwesome with NuxtJS but it doesn't work for unknown reasons.
Here is my package.json:
{
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview"
},
"devDependencies": {
"nuxt": "3.0.0-rc.6",
"sass": "^1.54.0",
"sass-loader": "^13.0.2"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^6.1.2",
"#fortawesome/free-regular-svg-icons": "^6.1.2",
"#fortawesome/free-brands-svg-icons": "^6.1.2",
"#fortawesome/free-solid-svg-icons": "^6.1.2",
"#fortawesome/vue-fontawesome": "^3.0.1",
"#nuxtjs/fontawesome": "^1.1.2"
}
}
Here is my nuxt.config.ts:
import { defineNuxtConfig } from 'nuxt'
// https://v3.nuxtjs.org/api/configuration/nuxt.config
export default defineNuxtConfig({
buildModules: ['#nuxtjs/fontawesome'],
fontawesome: {
icons: {
solid: ['faHome']
}
}
})
Now pages/index.vue:
<template>
<div>
Hello
</div>
</template>
As you can see I'm not even using any icon in this example, yet my app cannot start due to the following error in the Terminal (when I run npm run dev).
ℹ Vite client warmed up in 440ms 12:52:57
ℹ Vite server warmed up in 113ms 12:52:57
✔ Vite server built in 812ms 12:52:58
✔ Nitro built in 178 ms
[h3] [unhandled] H3Error: Cannot read properties of undefined (reading 'component')
at createError (file:///Users/thomasgysemans/Documents/GitHub/vue-portfolio/node_modules/h3/dist/index.mjs:191:15)
at Server.nodeHandler (file:///Users/thomasgysemans/Documents/GitHub/vue-portfolio/node_modules/h3/dist/index.mjs:381:21) {
statusCode: 500,
fatal: false,
unhandled: true,
statusMessage: 'Internal Server Error'
}
I don't understand this error and it seems like I am the only one to have it. Also, I'm new to NuxtJS and Vue.
I am following the documentation of #nuxtjs/fontawesome, and if I understand it well, I'm doing nothing wrong... Well I hope I made a simple mistake that will be solved lol. I really want to use FontAwesome, and it should work as FontAwesome itself provides a documentation on how to use their icons with Vue (but nothing related to NuxtJS).
Edit
Also, the app shows this as plain text, in a black background, but it doesn't show my beautiful "Hello".
{
"statusCode": 404,
"statusMessage": "Not Found",
"stack": []
}
Here is how to setup this
yarn add #fortawesome/fontawesome-svg-core #fortawesome/vue-fontawesome#latest-3
In a new /plugins/fontawesome.js file, put the following
import { library, config } from '#fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '#fortawesome/vue-fontawesome'
import { fas } from '#fortawesome/free-solid-svg-icons'
// This is important, we are going to let Nuxt worry about the CSS
config.autoAddCss = false
// You can add your icons directly in this plugin. See other examples for how you
// can add other styles or just individual icons.
library.add(fas)
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.component('font-awesome-icon', FontAwesomeIcon, {})
})
Inside of nuxt.config.ts
export default defineNuxtConfig({
css: [
'#fortawesome/fontawesome-svg-core/styles.css'
]
})
You should now be able to use it like this
<template>
<div>
<font-awesome-icon icon="fa-solid fa-user-secret" />
</div>
</template>
More info is available here: https://fontawesome.com/docs/web/use-with/vue/use-with#nuxt

react component module 'classProperties' isn't currently enabled

getting an error when executing my react module
'classProperties' isn't currently enabled (44:11):
}
43 | // componentDidUpdate or try this
> 44 | onClick = (e) => {
| ^
45 | e.preventDefault();
46 | const url = `${this.props.url}`;
47 | if(this.props.method === "GET"){
Add #babel/plugin-proposal-class-properties (https://git.io/vb4SL) to
the 'plugins' section of your Babel config to enable transformation.
I tried the solutions still get the error after re building.
Support for the experimental syntax 'classProperties' isn't currently enabled
package.json
{
"name": "blahmodule",
"version": "1.0.0",
"description": "a fetch module for our project",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "./node_modules/.bin/babel src --out-file index.js"
},
"peerDependencies": {
"react": "^16.6.6",
"react-dom": "^16.6.3",
"axios": "^0.19.0"
},
"author": "",
"license": "ISC",
"dependencies": {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.5",
"#babel/preset-env": "^7.4.5",
"#babel/preset-react": "^7.0.0",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"devDependencies": {
"#babel/plugin-proposal-class-properties": "^7.4.4",
"axios": "^0.19.0"
}
}
.babelrc
I tried changing the .babelrc to babel.config.js with module.exports, but still no success. also with and without "loose": true
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}
code from the beginning
import React, {Component} from 'react';
import axios from 'axios';
class MyFetch extends Component {
constructor(props){
super(props);
this.state = {
data:[],
startTime:'',
responseTime:''
}
}
componentWillMount(){
.....
}
// componentDidUpdate or try this
onClick = (e) => {
e.preventDefault();
const url = `${this.props.url}`;
if(this.props.method === "GET"){
axios.get(url).then( res => {
this.setState({
data: res.data
})
console.log(this.state.data)
})
}
else if(this.props.method === "POST"){
axios.get(url).then( res => {
this.setState({
data: res.data
})
console.log(this.state.data)
})
}
}
render(){
return (
<div>
{this.props.url ? (
<button onClick={this.onClick}>Get Response Time</button>
):(
null
)}
{this.state.responseTime ? (
<h3>{this.state.responseTime}</h3>
):(
null
)}
</div>
);
}
}
export default MyFetch;
Fixed it by adding webpack, i deleted .babelrc because i included in webpack.config.js. Now i guess i have a reason to use webpack in my projects.
var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, './'),
filename: 'index.js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: /(node_modules|bower_components|build)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/react'],
plugins:['#babel/plugin-proposal-class-properties']
}
}
}
]
},
externals: {
'react': 'commonjs react',
'reactDOM': 'react-dom'
},
};
For beginners, the best way to start working on React is to use create-react-app to create a ready to go clean boilerplate. Have a look at the docs and don't waste time configuring things but focus on writing code for your app.
https://github.com/facebook/create-react-app#npm

ReactJS: unexpected token '<'

Hello I tried to search in other questions but none of mentioned solutions I tried did not work for me.
When using command:
npm start
I have an error:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: D:/Kodilla/Projekty/webpack-to-do-app/src/index.js: Unexpected > token (6:4)
5 | ReactDOM.render(
6 | <App />,
| ^
7 | document.getElementById('app')
8 | );
Defined command in package.json:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack"
},
index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './containers/App';
ReactDOM.render(
<App />,
document.getElementById('app')
);
App.js file:
import React from 'react';
import uuid from 'uuid';
import style from './App.css';
class App extends React.Component {
constructor(props){
super(props);
this.state = {
data: []
};
}
addTodo(val){
const todo = {
text: val,
id: uuid.v4(),
};
const data = [...this.state.data, todo];
this.setState({data});
}
removeTodo(id) {
const remainder = this.state.data.filter(todo => todo.id !== id);
this.setState({data: remainder});
}
render() {
return (
<div className={style.TodoApp}>
Tutaj pojawią się komponenty naszej aplikacji.
</div>
);
}
}
export default App;
webpack.config.js file:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'app.bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader"
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}
]
}
};
.babelrc file:
{
"presets": [
["env", "react"]
]
}
Link to repository
Edit:
I tried the solution from post you suggest I duplicate but copied 1:1 did not work for me. I changed my webpack config to:
module: {
loaders: [...
{
test: /\.(js|jsx)?$/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}]
},
and problem still occurrs. I think I may be doing something wrong in other place than in mentioned example.
Edit 2:
I use babel-core#6.26.3 and babel-loader#7.1.5 because these are requirement of the project.
React and react-dom dependencies installed.
Presets: react. env, es2015, stage-0 installed by
npm install babel-preset-... --save-dev.
First suggested .babelrc config done:
"presets": ["react", "es2015", "stage-0"]
Error occurrs:
Couldn't find preset "#babel/preset-env" relative to directory
"...webpack-to-do-app\node_modules\css-loader"
What am I still doing wrong?
Problem was solved.
Things that helped:
1. Update presets from babel-env, babel-react to #babel/preset-env and #babel/preset-react. #babel-core was installed but babel-core stayed on place. Final set:
"devDependencies": {
"#babel/core": "^7.2.2",
"#babel/preset-env": "^7.2.3",
"#babel/preset-react": "^7.0.0",
"babel": "^6.23.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.4",
"css-loader": "^2.1.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"style-loader": "^0.23.1",
"webpack": "^4.28.2",
"webpack-cli": "^3.1.2"
},
2. Uninstall and install babel-loader which caused problem with requiring wrong version of babel itself.
#Alireza your suggestion was partially right. Thanks for helping.
please consider put below config on your .babelrc
{
"presets": ["react", "es2015", "stage-0"]
}
it should work.
also i see that you have nested array inside "presets". every preset should be one of presets elements.
and i'm strongly recommend that you use latest babel(version 7). when you upgrade to babel 7 you should download #babel/preset-react and #babel/preset-env and that should be enough.
and .babelrc will look like this:
{
"presets": [
"#babel/react",
"#babel/env"
]
}

Jest encountered an unexpected token

Not sure why it's complaining on this line:
const wrapper = shallow(<BitcoinWidget {...props} />);
/Users/leongaban/projects/match/bitcoin/src/components/bitcoinWidget.test.js: Unexpected token (17:26)
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
- To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
- If you need a custom transformation specify a "transform" option in your config.
- If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
15 |
16 | describe('when rendering', () => {
>17 | const wrapper = shallow(<BitcoinWidget {...props} />);
18 | ^
19 | it('should render a component matching the snapshot', () => {
20 | const tree = toJson(wrapper);
Entire test:
import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
// Local components
import BitcoinWidget from './bitcoinWidget';
const props = {
logo: 'foobar',
coin: {
price: 0
},
refresh: jest.fn()
}
describe('when rendering', () => {
const wrapper = shallow(<BitcoinWidget {...props} />);
it('should render a component matching the snapshot', () => {
const tree = toJson(wrapper);
expect(tree).toMatchSnapshot();
expect(wrapper).toHaveLength(1);
});
});
The component
import React from 'react';
const BitcoinWidget = ({ logo, coin : { price }, refresh }) => {
return (
<div className="bitcoin-wrapper shadow">
<header>
<img src={logo} alt="Bitcoin Logo"/>
</header>
<div className="price">
Coinbase
${price}
</div>
<button className="btn striped-shadow white" onClick={refresh}>
<span>Refresh</span>
</button>
</div>
);
}
export default BitcoinWidget;
And my package.json
{
"name": "bitcoin",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.18.0",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-redux": "^5.0.7",
"react-scripts": "1.1.5",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"test": "yarn run test-jest:update --verbose --maxWorkers=2",
"test-jest:update": "jest src --updateSnapshot",
"test-jest": "jest src"
},
"now": {
"name": "bitcoin",
"engines": {
"node": "8.11.3"
},
"alias": "leongaban.com"
},
"jest": {
"verbose": true,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/client/assetsTransformer.js"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
]
},
"devDependencies": {
"enzyme": "^3.4.4",
"enzyme-to-json": "^3.3.4",
"jest": "^23.5.0"
}
}
Add this in your package.json jest config.
"transform": {
"\\.js$": "<rootDir>/node_modules/babel-jest"
},
Let me know if the issue still persists.
For anyone using create-react-app, only certain jest configurations can be changed in package.json when using create-react-app.
I have issues with Jest picking up an internal library, Jest would display 'unexpected token' errors wherever I had my imports from this library.
To solve this, you can change your test script to the below:
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",
For anyone who struggled with this issue and none of the above answers worked for them.
After a long time of searching, I reached for this solution:
edit your jest.config.js to add transformIgnorePatterns
//jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
testMatch: ["**/__tests__/**/*.ts?(x)", "**/?(*.)+(test).ts?(x)"],
transform: {
"^.+\\.(js|ts)$": "ts-jest",
},
transformIgnorePatterns: [
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.js$",
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.ts$",
"/node_modules/(?![#autofiy/autofiyable|#autofiy/property]).+\\.tsx$",
],
}
put the packages that you want to ignore inside [] and separate them by |
in my case [#autofiy/autofiyable|#autofiy/property]
I also encountered the same error while setting up Jest in my React app created using Webpack. I had to add #babel/preset-env and it was fixed. I have also written a blog article about the same.
npm i -D #babel/preset-env
And then add this in "presets" in .babelrc file. E.g.
{
"presets": ["#babel/react", "#babel/env"]
}
https://medium.com/#shubhgupta147/how-i-solved-issues-while-setting-up-jest-and-enzyme-in-a-react-app-created-using-webpack-7e321647f080?sk=f3af93732228d60ccb24b47ef48d7062
I added the jest update to my package.json
"jest": {
"transformIgnorePatterns": [
"node_modules/(?!(<package-name>|<second-package-name>)/)"
]
},
Feel free to remove the |<second-package-name> if not required.
You can also do it as part of your script as mentioned #paulosullivan22
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<package-name>)/)'"
In my case, the issue was that I was importing the original module in the mocked module:
import urlExist from "url-exist";
async function stubbedUrlExist(): Promise<boolean> {
// do something
}
export default stubbedUrlExist;
The solution was to not import url-exist in the url-exist mock. This might have lead to a circular import. Jest was perhaps catching this error in a generic try<>catch block dealing with the loading of modules.
Below works for me.
Create babel.config.js file.
module.exports = {
presets: [
[ '#babel/preset-env', { targets: { esmodules: true } } ],
[ '#babel/preset-react', { runtime: 'automatic' } ],
],
};
I updated some dependencies (react, jest and others), and I also got the error:
Jest encountered an unexpected token - SyntaxError: Cannot use import statement outside a module
I had dev dependencies with needed to be transpiled.
What I did first was start all over:
$ jest --init
A jest.config.js is now generated (before I just had Jest configuration in my package.json).
In the error message under details you can see the reporting module, for me it looked like this:
Details: /<project_root>/node_modules/axios/index.js:1
Adding the following transform ignore in jest.config.js solved my problem:
transformIgnorePatterns: [
"node_modules/(?!axios.*)"
],
The axios module was now nicely transpiled and gave no more problems, hope this helps!
https://jestjs.io/docs/27.x/getting-started
Below works for me
module.exports = {
presets: [
["#babel/preset-env", { targets: { node: "current" } }],
"#babel/preset-typescript", "#babel/react"
]
};
could not get it working with transforms, I ended up mocking the dependency:
Create a file: <path>/react-markdown.js
import React from 'react';
function ReactMarkdown({ children }){
return <>{children}</>;
}
export default ReactMarkdown;
On jest.config.js file add:
module.exports = {
moduleNameMapper: {
'react-markdown': '<path>/mocks/react-markdown.js',
},
};
credits to juanmartinez on https://github.com/remarkjs/react-markdown/issues/635

Webpack unexpected token in JS file

I'm learning react and flux, and in lesson 1 the tutorial has failed me.
This tutorial immediately breaks on 'npm start' with the following errors:
ERROR in ./src/js/main.js
Module parse failed: /Users/me/Projects/egghead-flux/src/js/main.js Unexpected token (4:16)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (4:16)
at Parser.pp$4.raise (/Users/me/Projects/egghead-flux/node_modules/acorn/dist/acorn.js:2221:15)
It doesn't seem to understand ReactDOM.render(<App />, document.getElementById('main')); I assume parsing the JSX <App /> part is failing.
Has anyone encountered this issue before? Removing / reinstalling node modules does nothing. Is there some setup step missing from the video?
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
ReactDOM.render(<App />, document.getElementById('main'));
App.js
import React from 'react';
export default class App extends React.Component {
render(){
return <h1>Flux</h1>
}
}
webpack.config.js
module.exports = {
entry: './src/js/main.js',
output:{
path:'./dist',
filename: 'bundle.js',
publicPath: '/'
},
devServer: {
inline: true,
contentBase: './dist'
},
module: {
loaders: [
{
test: '/\.jsx?$/',
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query:{
presets: ['es2015', 'react']
}
}
]
}
}
package.json
{
"name": "egghead-flux",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"flux": "^3.1.0",
"react": "^15.3.2",
"react-dom": "^15.3.2",
"react-router": "^3.0.0"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-loader": "^6.2.7",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2"
}
}
Turns out:
test: '/\.jsx?$/',
should be:
test: /\.jsx?$/,
Dammit.

Categories

Resources