React JSX file giving error "Cannot read property 'createElement' of undefined" - javascript

I have a file test_stuff.js that I am running with npm test
It pretty much looks like this:
import { assert } from 'assert';
import { MyProvider } from '../src/index';
import { React } from 'react';
const myProvider = (
<MyProvider>
</MyProvider>
);
describe('Array', function() {
describe('#indexOf()', function() {
it('should return -1 when the value is not present', function() {
assert.equal(-1, [1,2,3].indexOf(4));
});
});
});
Unfortunately, I get the error
/Users/me/projects/myproj/test/test_stuff.js:11
var myProvider = _react.React.createElement(_index.MyProvider, null);
^
TypeError: Cannot read property 'createElement' of undefined
at Object.<anonymous> (/Users/me/projects/myproj/test/test_stuff.js:7:7)
What does that mean? I am importing React from 'react' successfully, so why would React be undefined? It is _react.React, whatever that means...

To import React do import React from 'react' You add brackets when the thing you are importing is not the default export in that module or file. In case of react, it's the default export.
This might apply to your other imports depending on how you defined them.

import React, { Component } from 'react'
This worked for me. I'm not sure why it fixed my version of this issue, though. So if you are someone who stumbled upon this problem and you use create-react-app as your starting boilerplate, this way of importing React will do the trick. (as of Oct '18, lol)

For those who are working ReactJS with TypeScript.
import * as React from 'react';

This error occured to me due to carelessness. It's actually
import React from 'react';
Brackets are for named exports such as this:
import React, { useState, useEffect } from 'react';

This issue occurred while importing React from react, I placed it inside curly brackets.
Please do this:
import React, {useState} from "react";
Instead of:
import {React, useState} from "react";

Trying to use destructor for importing the React object may cause you problems like this import {React} from 'react';.
This might be the cause of the error 90% of the time running this code above.
rather use:
import React from 'react';
And then you can access any member of the React class via:
React.

Change:
import { React } from 'react' to import React from 'react'
Because React is a default export and you don’t need curly braces for any default exports.

If in case you need to import multiple classes from 'react', you can have an alias for them except React. Something like,
import React, * as react from 'react';

React is exported by default in that module, no need {}.

I got this when trying to mock a component when unit testing but was not setting it up correctly
What I was doing that caused the error:
jest.mock("./SomeComponent", () => {
return <div>MockSomeComponent</div>
});
What I needed to do:
jest.mock("./SomeComponent", () => {
return () => <div>MockSomeComponent</div>
});

This error can be occured due to carelessness. Please add
import React from 'react'
It will be resolved after that

Related

react-bootstrap-table-toolkit Search Import Error

I wanted to use React Bootstrap Table in my project and I'm getting the following error.
Uncaught ReferenceError: arguments is not defined at Object../node_modules/react-bootstrap-table2-toolkit/lib/src/search/SearchBar.js
here is the following import which are referred from their official website.
import ToolkitProvider, {Search} from 'react-bootstrap-table2-toolkit';
const {SearchBar} = Search;
where search can not be found from this import.
Here is an easy fix, I resolved this issue by changing the import
from
import ToolkitProvider, {Search} from 'react-bootstrap-table2-toolkit';
to
import ToolkitProvider, {Search} from 'react-bootstrap-table2-toolkit/dist/react-bootstrap-table2-toolkit';
The fix isnt still in place; change your import pointing to the .min file of toolkit
replace this
import ToolkitProvider, { CSVExport } from "react-bootstrap-table2-toolkit";
with this
import ToolkitProvider , { CSVExport } from 'react-bootstrap-table2-toolkit/dist/react-bootstrap-table2-toolkit.min'

React JS, props validation

New to React JS, props validation practise as follows:
import React from 'react';
import PropTypes from 'prop-types';
class App extends React.Component {
render() {
return (
<div>
<h3>String : {this.props.propstring}</h3>
</div>
);
}
}
App.propTypes = {
propstring : PropTypes.string
}
App.defaultProps = {
propstring : "My Name"
}
export default App;
import React, { component } from 'react';
import ReactDOM from 'react-dom';
import App from './AppProp.js';
ReactDOM.render(<App />,document.getElementById('root'));
Getting an error as:
TypeError: Class extends value undefined is not a constructor or null.
What am I missing here and how can I resolve the above error?
There are 2 possible problems. Most probably you're importing { component }(like you do in your index file, which is wrong), instead of { Component } somewhere in your code and trying to extend component which doesn't exist.
The other reason is that you might be circularly importing classes, but I doubt it. Also, is your file called AppProp.js?
Post the stack trace and it would also help if you post all the components you're using. Post your package.json as well, as you might be using wrong absolute paths.
The code is perfectly fine. I executed it on my local machine and it ran fine.
The only issue you may be facing is to with
circularly importing classes, which is apparently a limitation
Know more from the resource:
https://esdiscuss.org/topic/how-to-solve-this-basic-es6-module-circular-dependency-problem

Getting 'React' must be in scope when using JSX

I am new to react and I tried the following code
person.js
const element = <h1>Hello world</h1>;
export default element;
App.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import Person from '../src/person/person';
function Hello() {
return Person.element;
}
class App extends Component {
render() {
return (
<div className="App">
<Hello></Hello>
</div>
);
}
}
export default App;
But getting the below errors
work/my-app/src/person/person.js
3:17 error 'React' must be in scope when using JSX react/react-in-jsx-scope
When I changed to a simple hello word as below, then it works fine.
person.js
const element = 'hello world';
export default element;
I tried with different ways by checking different forum
importing the ReactDom
in person.js changed to module.exports=element
The use of HTML within JS code is known as JSX. The <h1>...</h1> is JSX. You need to import React before you use JSX. Simply shift the import statements before any use of JSX.
person.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import Person from '../src/person/person';
const element = <h1>Hello world</h1>;
export default element;
You need to import React in every file that exports a component (App in this case).
The latest React 17 Version: No need to include React in the scope
If you are struggling with ESlint or run-time CRA warnings, follow these temporary steps to fix until CRA v4 is released: https://github.com/facebook/create-react-app/issues/9850

"Import in body of module; reorder to top import/first" Across Many Files

I have the same error as this answer, except instead of it just occurring in one file it is occurring in many; once I fix it for one file, another just pops up with the same error. I've seen this answer but whenever I run react-scripts start a node_modules folder is created in my src, so that solution isn't viable.
It would be too time consuming to have to fix every file that has this error every time I compile, so how can I get rid of this error? It seems to just be an eslint issue.
you will get this error if you declare variable in between your imports,
import React from 'react';
import axios from 'axios';
const URL = process.env.REACT_APP_API_BASE;
import demoXLXSFile from '../../assets/others/Demo.xlsx';
import './student.list.styles.scss';
declare variables after importing everything,
import React from 'react';
import axios from 'axios';
import demoXLXSFile from '../../assets/others/Demo.xlsx';
import './student.list.styles.scss';
const URL = process.env.REACT_APP_API_BASE;
I found this issue while I was using React.lazy in my existing project. I got this error Failed to compile. :- Import in body of module; reorder to top import/first (with create-react-app).
import React from 'react';
import SelectField from '../inputs/SelectField';
const Questions = React.lazy(() => import('./questions'))
import _ from 'lodash';
Solution:-
Only reorder the position i.e. put all import on top then react.lazy.
import React from 'react';
import SelectField from '../inputs/SelectField';
import _ from 'lodash';
const Questions = React.lazy(() => import('./questions'))
I got this same error when I added an extra semicolon ';' at the end of an import statement.
I suggest removing any extraneous semicolons. This should make the error go away.
Moving every import statement to the top of the file solves the issue.
Happened to me when I put require before import like this:
require('dotenv').config()
import React from 'react';
import ReactDOM from 'react-dom';
...
Solution: Put the require after the imports
If You are using Component Lazy loading then always put lazy load component import code below normal import code.
Correct Example
import First from './first'
const Second = React.lazy(()=>import("./Second))
Incorrect Example
const Second = React.lazy(()=>import("./Second))
import First from './first'
I came across this issue too. I found that you must import all ES6 modules at the top level of your JavaScript files."... the structure of ES6 modules is static, you can’t conditionally import or export things. That brings a variety of benefits.
This restriction is enforced syntactically by only allowing imports and exports at the top level of a module:"
From Dr. Axel Rauschmayer’s Exploring JS:
Wrong
1.
import React ,{useState ,useEffect} from 'react';
import './App.css';
import Post from './Post';
import db from "./firebase"
Right
2.
import React ,{useState ,useEffect} from 'react';
import './App.css';
import Post from './Post';
import db from "./firebase.js"
//this is code firebase.js
const db = firebaseApp.firestore();
const auth = firebase.auth();
const storage = firebase.storage();
export default {db,auth,storage};
When I change the firebase into firebase.js in Snippet 2.
My Error vanished
I had forgotten to add from.
Before:
import UpperBlock;
After:
import UpperBlock from "../components/dashboard/shared/UpperBlock";
Make sure you import well your component and then stop the server and restart it again. It worked for me.
I forgot to add {Component} after importing 'react' library to my project, this solved my issue.
Move all of your imports to the top of the file.
Even in case of a require (that is written in between import statements), this error will come.
e.g.
import 'some_module';
require('some_file');
import 'some_other_module');
This would result in an error.
You would want to do this instead:
import 'some_module';
import 'some_other_module');
require('some_file');
I was facing the same issue when I installed chat.js library in my reactJs project. I solved this issue by moving my chart.Js import to the index.js file
index.js file:
import React from "react";
import ReactDOM from "react-dom";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js"; <--- imported
import "./index.css";
import App from "./App";
ChartJS.register(ArcElement, Tooltip, Legend); <---- imported
If you're experiencing this error in modern versions of react(current version 18.0.0) make sure you're making all your imports before the ReactDOM.createRoot declaration.
For example, I got the error with:
import App from "./App";
import reportWebVitals from "./reportWebVitals";
const root = ReactDOM.createRoot(document.getElementById("root"));
import { Provider } from "./context";
This will result in an error. Instead, import everything before the createRoot:
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "./context";
const root = ReactDOM.createRoot(document.getElementById("root"));
This will fix the error. Simple fix but it's easy to miss
If I put double Semicolon behind the importing statement than I got "error".you can see difference between two pictures in import './index.css'; is different
For Example :-
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';;
import 'tachyons';
import {robots} from "./Robots";
import reportWebVitals from './reportWebVitals';
import CardList from './CardList';

importing TypeScript vs ES2015

I am trying to figure out why TypeScript is not picking up the "default export" of react. E.g. in my JavScript files I was using:
import React from 'react';
import ReactDOM from 'react-dom';
But in typescript I have to use (after some googling):
import * as React from "react"
import * as ReactDOM from "react-dom"
I am just starting out with a fresh project after being unable to import my existing project and g et VS2k15 to compile it.
What is the difference, if any? Is there a way to specify a "Module 'react' has no default export".
I can see in the React file there is
declare module "react" {
export = __React;
}
Is that not considered a default export
I also tried
import __React from "react"
but get the same error.
A default export is just giving one of the exports the alias "default". You can do this using the following syntax:
export default function __React {
//do work
}
You can also use the following syntax:
function __React {
//do work
}
export {__React as default};

Categories

Resources