I know JS and React, but have zero experience with TS.
I'm following a tutorial on YT, but figured I'd use TS to learn it, instead of JS.
And so after some setting up, I figured I'm ready to continue with the tutorial. However...
This works with JS:
index.html (Django template):
[irrelevant html setup]
<body>
<div id="main">
<div id="app"></div>
</div>
<script src="{% static "frontend/main.js" %}"></script>
</body>
App.js:
import React from "react";
import { render } from "react-dom";
const App = () => {
return <h1>Testing React code</h1>;
};
export default App;
const appDiv = document.getElementById("app");
render(<App />, appDiv);
index.js:
import App from "./components/App";
// that's it. The import is all there is in index.js
This is later compiled by babel-loader to main.js, which I'll not paste here, since it unreadable anyway. However, it does render the text from App.js.
When I have the analogical setup with TS, it doesn't work for some reason.
App.tsx:
import React, { FC } from "react";
import { render } from "react-dom";
const App: FC = () => {
return <h1>Testing React code</h1>;
};
export default App;
const appDiv = document.getElementById("app");
render(<App />, appDiv);
index.ts is the same as index.js, html file also remains unchanged.
I run tsc compiler, then run dev script that uses babel-loader. File main.js is created, but it has a one long line, and nothing is rendered when I run server.
Files App.js and index.js are created during compilation, but index.js has just export {} in it.
I suppose this is due to a difference in how TS and JS work, but I'm not sure what to even look for. I get no error messages.
I have an application I am transitioning to an Exist-db app and I am getting a couple of error messages with attempting to include a React module. I know what they're trying to tell me and what the problem is, but I have no idea how to fix it from within the app.
This project needs to include Mirador integration, following the instructions for "Approach 1" here: https://github.com/ProjectMirador/mirador/wiki/M3-Embedding-in-Another-Environment#in-an-html-document-with-javascript. I have not made any modifications to their example code in the codesandbox link (which is https://codesandbox.io/s/react-example-0uwig) if you want to look at it directly, but here is what I have for index.js if it will help.
import ReactDOM from "react-dom";
import React, { Component } from "react";
import mirador from "mirador";
class Mirador extends Component {
componentDidMount() {
const { config, plugins } = this.props;
mirador.viewer(config, plugins);
}
render() {
const { config } = this.props;
return <div id={config.id} />;
}
}
export default Mirador;
ReactDOM.render(
<Mirador config={{ id: "mirador" }}/>,
document.getElementById("root")
);
I call to index.js through an xslt template on the xsl constructing the final look and feel of the page:
<xsl:template name="mirador_javascript">
<div id="mirador"/>
<script>
<xsl:attribute name="type">module</xsl:attribute>
<xsl:attribute name="src">http://localhost:8080/exist/apps/mwjl-app/resources/javascript/index.js</xsl:attribute>
</script>
</xsl:template>
On doing so, however, I get the following error: Uncaught SyntaxError: expected expression, got '<'. If I change index.js to a .jsx file to resolve the issue I get the following error instead: Loading module from “http://localhost:8080/exist/apps/mwjl-app/resources/javascript/index.jsx” was blocked because of a disallowed MIME type (“application/octet-stream”).Any thoughts about where I'm going wrong in constructing things or how I need to modify the Javascript to get this working? The more simple method they outline on that link above doesn't work properly from within exist-db, so I think it's React or this project is a wash.
When i want to create an element without JSX it shows me this error 'React' is not defined no-undef. I am a beginner. I don't know what is the problem. Can anyone help
import logo from './logo.svg';
import './App.css';
const app = React.createElement("h1", null, "Without JSX"); // Showing an error
function App() {
return (
<div className="App">
{app};
</div>
);
}
export default App;
These messages are shown in VS code Terminal.
Failed to compile.
./src/index.js
SyntaxError: E:\react_js_course\src\index.js: Unexpected token, expected "," (11:2)
Failed to compile.
src\App.js
Line 4:13: 'React' is not defined no-undef
Search for the keywords to learn more about each error.
A couple points just based on the code you provided:
You are using JSX in your example: your App component returns JSX, so React should be in scope to do that.
You are explicitly using the React method createElement so React should be available in this file.
To fix both issues add import React from 'react'; at the top of this file.
import React from 'react' is required for writing code in JSX and alternative you use ES7 snippet which help to auto populate the code
enter image description here
Img-extension ss
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
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'