I am trying to make ReactJS work with rails using this tutorial. I am getting this error:
Uncaught ReferenceError: React is not defined
But I can access the React object in browser console
I also added public/dist/turbo-react.min.js as described here and also added //= require components line in application.js as described in this answer to no luck. Additionally,
var React = require('react') gives the error:
Uncaught ReferenceError: require is not defined
Can anyone suggest me on how to resolve this?
[EDIT 1]
Source code for reference:
This is my comments.js.jsx file:
var Comment = React.createClass({
render: function () {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.comment}
</div>
);
}
});
var ready = function () {
React.renderComponent(
<Comment author="Richard" comment="This is a comment "/>,
document.getElementById('comments')
);
};
$(document).ready(ready);
And this is my index.html.erb:
<div id="comments"></div>
If you are using Babel and React 17, you might need to add "runtime": "automatic" to Babel config.
In .babelrc config file this would be:
{
"presets": [
"#babel/preset-env",
["#babel/preset-react", {"runtime": "automatic"}]
]
}
I got this error because I was using
import ReactDOM from 'react-dom'
without importing react, once I changed it to below:
import React from 'react';
import ReactDOM from 'react-dom';
The error was solved :)
I was able to reproduce this error when I was using webpack to build my javascript with the following chunk in my webpack.config.json:
externals: {
'react': 'React'
},
This above configuration tells webpack to not resolve require('react') by loading an npm module, but instead to expect a global variable (i.e. on the window object) called React. The solution is to either remove this piece of configuration (so React will be bundled with your javascript) or load the React framework externally before this file is executed (so that window.React exists).
If you are using Webpack, you can have it load React when needed without having to explicitly require it in your code.
Add to webpack.config.js:
plugins: [
new webpack.ProvidePlugin({
"React": "react",
}),
],
See http://webpack.github.io/docs/shimming-modules.html#plugin-provideplugin
Possible reasons are 1. you didn't load React.JS into your page, 2. you loaded it after the above script into your page. Solution is load the JS file before the above shown script.
P.S
Possible solutions.
If you mention react in externals section inside webpack configuration, then you must load react js files directly into your html before bundle.js
Make sure you have the line import React from 'react';
Try to add:
import React from 'react'
import { render } from 'react-dom'
window.React = React
before the render() function.
This sometimes prevents error to pop-up returning:
React is not defined
Adding React to the window will solve these problems.
Adding to Santosh :
You can load React by
import React from 'react'
I know this question is answered. But since what worked for me isn't exactly in the answers, I'll add it here in the hopes that it will be useful for someone else.
My index.js file looked like this when I was getting Uncaught ReferenceError: React is not defined.
import {render} from 'react-dom';
import App from './App';
render(<App />, document.getElementById("root"));
Adding import React from 'react'; at the top of the file fixed it.
Now my index.js looks like this and I don't get any error on the console.
import React from 'react';
import {render} from 'react-dom';
import App from './App';
render(<App />, document.getElementById("root"));
Please note I made no change in webpack.config.js or anywhere else to make this work.
import React, { Component, PropTypes } from 'react';
This may also work!
If you're using TypeScript, make sure that your tsconfig.json has "jsx": "react" within "compilerOptions".
I was facing the same issue.
I resolved it by importing React and ReactDOM like as follows:
import React from 'react';
import ReactDOM from 'react-dom';
I got this error because in my code I misspelled a component definition with lowercase react.createClass instead of uppercase React.createClass.
I got this error because I used:
import React from 'react';
while working with React, Typescript and Parcel
Changing it to:
import * as React from 'react';
Solved the problem as suggested by https://github.com/parcel-bundler/parcel/issues/1199#issuecomment-381817548
Sometimes the order of import can cause this error, if after you have followed all the steps above and still finds it hard on you, try making sure the react import comes first.
import React from 'react'
import { render } from 'react-dom'
before any other important you need to make.
The displayed error
after that import react
Finally import react-dom
if error is react is not define,please add ==>import React from 'react';
if error is reactDOM is not define,please add ==>import ReactDOM from 'react-dom';
To whom using CRA and ended up to this question, can use customize-cra and react-app-rewired packages to override babel presets in CRA.
To do this, create a config-overrides.js in the root and paste this code snippet in it.
const { override, addBabelPreset } = require('customize-cra');
module.exports = override(
addBabelPreset('#emotion/babel-preset-css-prop'),
addBabelPreset([
'#babel/preset-react',
{
runtime: 'automatic',
importSource: '#emotion/react',
},
]),
);
And update scripts in package.json with the ones below.
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
I got this because I wrote
import react from 'react'
instead of
import React from 'react'
Related
I find a weird behaviour when writing my vite program,
import { Store } from '#decky.fx/react-native-essentials/lib/index';
the code above is working fine, but if i change it into
import { Store } from '#decky.fx/react-native-essentials';
Store will yield undefined
I have to load all modules like this
import All from '#decky.fx/react-native-essentials';
All.Store // this is working
package json for the modules are like this
...
"main": "lib/index.js",
"types": "lib/index.d.ts",
...
any ideas why it behave like this?
the repository is at https://github.com/deckyfx/react-native-essentials/example
Should be able to destructure modules like how react library does
react, {useState} from "react"
Hey not sure but i think its happenig because import { Store } from '#decky.fx/react-native-essentials' is looking for store in the react-native-essentials but its not in that file its in the sub-folder of it react-native-essentials/lib/index not in the root and so that's why you not able to destructure it from the react-native-essentials and as for why this is working import All from '#decky.fx/react-native-essentials'; its because you importing everything from the file even its subfiles/folders .
And in this case react, {useState} from "react" react have everything in the "react" file so that's why this works import{useSatte} from react
We would like to create bundle.js from React and webpack, where a per build configuration is included and made available to the React code, but we are not sure how to go about doing this.
The idea would be to be to do something like:
npm run build -- config="config123.json"
And then have the generated bundle.js include that configuration, such that it could be used by the root container. Something like:
import React from 'react';
import ReactDOM from 'react-dom';
import RootContainer from './containers/main-container';
ReactDOM.render(
<RootContainer config={configPassedByBuildProcess}/>,
document.getElementById('app')
);
Is this possible and if so, how should we approach this?
No, I don't believe that you can pass a file on build, from what I know the only thing that you can pass is a string like an ENV variable. You could import the config123.json file like this
import React from 'react';
import ReactDOM from 'react-dom';
import RootContainer from './containers/main-container';
import config from '/path/to/config123.json'
ReactDOM.render(
<RootContainer config={config}/>,
document.getElementById('app')
);
You may need a JSON loader for importing JSON files
After a bit of experimenting, the solution I have found is to use Webpack's DefinePlugin, since this provides a way of doing string substitution during webpack's build phase.
In my React code I defined:
// Will be substituted by webpack's DefinePlugin. Not an error.
const bundleConfig = BUNDLE_CONFIG;
and then in my webpack.config.js I first load my config (hard coded for now):
// The path can be pulled in via 'process.args' and parsed as appropriate
const bundleConfig = fs.readFileSync('bundle-config/default-config.json', 'UTF-8');
module.exports = {
plugins: [
new webpack.DefinePlugin({
'BUNDLE_CONFIG': bundleConfig
})
]
}
Note that if for some reason we want to build with a missing or undefined bundleConfig, then the right substitution would likely be the string (not the keyword) 'undefined' , to keep the code valid, such that:
const bundleConfig = 'undefined';
module.exports = {
plugins: [
new webpack.DefinePlugin({
'BUNDLE_CONFIG': bundleConfig
})
]
}
Just one extra thing was the configuration of the package.json (scripts section only):
{
"scripts": {
"build": "run() { NODE_ENV=production && webpack -p $1; }; run",
}
}
This allow passing in the path to the webpack.conf.js script, when we call:
npm run build /path/to/config.json
import React from 'react';
// import ReactDOM from 'react-dom';
import ReactDOM from 'react-dom/dist/react-dom.min';
import {Alert} from 'reactstrap';
class AlertLine extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true
};
}
onDismiss = () => {
this.setState(
{
visible: false
}
);
};
render() {
return (
<div>
<Alert color="success" isOpen={this.state.visible} toggle={this.onDismiss}>
<strong>Success!</strong> You successfully read this important alert message.
</Alert>
</div>
);
}
}
ReactDOM.render(
<AlertLine/>,
document.getElementById('root')
);
ReactDOM.render() works just fine with 'react-dom' for development. However, as soon as I try import minified 'react-dom.min' instead of 'react-dom', render() goes unresolved and nothing happens. I can't find render() from content assist(ctrl + space) neither.
I've installed react#15.6.1 and react-dom#15.6.1 with npm and they're on 'npm list'. Then I tried reinstall them but that didn't work.
In your case, you have to use import ReactDOM from 'react-dom' because import doesn't mean "file import", it means "ES6 module import".
To minify your bundle file, try uglifyjs-webpack-plugin (if you're using webpack) or minifyify (if you're using browserify)
Non-module
Node modules loaded with require / import must populate an exports object with
everything that the module wants to make public.
stackoverflow.com/a/14914442/6836839
react-dom.min.js is used as a simple js library, you can't import / require
Install
Since you can't require / import, you need to load it as a normal js script:
<!-- index.html -->
<script src="node_modules/react-dom/dist/react-dom.min.js"></script>
Use
// Just call it...
ReactDOM.render(component, document.getElementById('root'))
Note
If you load React from a tag, these top-level APIs are available on the ReactDOM global.
If you use ES6 with npm, you can write import:
import ReactDOM from 'react-dom'
If you use ES5 with npm, you can write:
var ReactDOM = require('react-dom');
https://facebook.github.io/react/docs/react-dom.html
Import name is not same as the component name which you are exporting.
When you Import a component in a common Index.js file and you are Importing a component(import Header from './components/Header';).
Header should be different from export default headerComponent; name
When running npm build with:
"build": "browserify -t [ babelify --presets [ es2015 react ] ] app/assets/app.jsx -o public/javascripts/app.js"
I am getting following error:
Error: Cannot find module 'components/maininput.jsx' from 'C:\Users\Work\Documents\NetBeansProjects\Project\app\assets'
Project structure looks like this:
app
|
└────assets
│ app.jsx
|
└───components
maininput.jsx
import in app.jsx looks like this:
import React from 'react';
import ReactDOM from 'react-dom';
import { MainInput } from '../components/maininput.jsx'
export in maininput.jsx looks like this:
export default class MainInput extends React.Component {
//some code and render()
}
I also created GulpFile and also there getting same error:
{ Error: Cannot find module '../components/maininput.jsx'
EDIT:
I have found out that it is working only if I provide full path to component, which is strange. Anyone knows what might cause this problem? Probably some enviroment variable or ?
Use ./ at the beginning of your import path:
import { MainInput } from './components/maininput.jsx'
I just started with React.js and I am unable to import component.
I have this structure as followed by this tutorial (YouTube link) :
-- src
----| index.html
----| app
------| index.js
------| components
--------| MyCompontent.js
This is my index.js:
import React from 'react';
import { render } from 'react-dom';
import { MyCompontent } from "./components/MyCompontent";
class App extends React.Component {
render() {
return (
<div>
<h1>Foo</h1>
<MyCompontent/>
</div>
);
}
}
render(<App />, window.document.getElementById('app'));
This is MyComponent.js:
import React from "react";
export class MyCompontent extends React.Component {
render(){
return(
<div>MyCompontent</div>
);
}
}
I am using this webpack file (GitHub link).
However, when I run this, my module fails to load.
I get this error in the browser console:
Error: Cannot find module "./components/MyCompontent"
[WDS] Hot Module Replacement enabled. bundle.js:631:11
[WDS] Errors while compiling. bundle.js:631:11
./src/app/index.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./components/MyCompontent in /home/kuno/code/react-hoteli/src/app
resolve file
/home/kuno/code/react-hoteli/src/app/components/MyCompontent doesn't exist
/home/kuno/code/react-hoteli/src/app/components/MyCompontent.webpack.js doesn't exist
/home/kuno/code/react-hoteli/src/app/components/MyCompontent.web.js doesn't exist
/home/kuno/code/react-hoteli/src/app/components/MyCompontent.js doesn't exist
/home/kuno/code/react-hoteli/src/app/components/MyCompontent.json doesn't exist
resolve directory
/home/kuno/code/react-hoteli/src/app/components/MyCompontent/package.json doesn't exist (directory description file)
/home/kuno/code/react-hoteli/src/app/components/MyCompontent doesn't exist (directory default file)
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent]
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.webpack.js]
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.web.js]
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.js]
[/home/kuno/code/react-hoteli/src/app/components/MyCompontent.json]
# ./src/app/index.js 11:20-56 bundle.js:669:5
Can't figure out what went wrong here.
For anyone coming here without a typo, and is using Webpack, be sure to check for a clause like this:
resolve: {
extensions: [".jsx", ".js"]
},
in your webpack.config.js.
This tells your transpiler to resolve statements like:
import Setup from './components/Setup'
to
import Setup from './components/Setup.jsx'
This way you don't need the extension.
You have a typo in your import. You're requesting MyCompontent. Change to:
import MyComponent from "./components/MyComponent";
And all typos as well.
You can try to import MyCompontent from "./components/MyCompontent.js"
like this
import MyCompontent from "./components/MyCompontent.js";
You have written that the filename is MyComponent.js.
Thus, your import should look like
import { MyCompontent } from './components/MyComponent.js'
The problem for me was that import line was not generated correctly. I have this scenario:
--src
----elements
-----myCustomText.tsx
this is myCustomText.tsx file:
export interface Props {
text: string;
}
const MyCustomText = ({ text }: Props) => (
<Text>{text}</Text>
);
export default MyCustomText
And the generated import was this:
import MyCustomText from '../../elements/MyCustomText';
and I changed it to this:
import MyCustomText from '../../elements/myCustomText'
I don't know why the generated import line was generated automatically wrong.
I found myself here without a typo and without a webpack issue.
The solution for me was to restart the typescript server via VS Code.
I just had this issue, no type or webpack config issues.
What fixed it was changing the import from relative to the app root directory to relative to the file:
import MyComponent from "src/components/MyComponent";
to
import MyComponent from "../components/MyComponent";
If you're getting this from Visual Studio Code auto-importing via the shortest route, you can change it so it imports relatively. By going here:
menu File → Preferences → Settings → User Settings,
"typescript.preferences.importModuleSpecifier": "relative"
export 'Component' (imported as 'Component') was not found in 'react'
if you find your self stuck with this error simply go to mini-create-react-context, and go to cjs, and go to index.js and add "React" example: you will find this (Component) solution (React.Component) only if you extends to React.Component in you pages
Note: I have only used this on VS Code