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
Related
I used npm init react-app appname which creates, among other files, App.js. In that file is a function component:
function App() {
return (
<SomeJSX />
);
}
I edited the function component into a class component, like so:
class App extends React.Component{
render() {
return (
<TheSameJSX />
);
}
}
Now, when I run npm start, I get an error:
Failed to compile
src/App.js
Line 4:19: 'React' is not defined no-undef
Search for the keywords to learn more about each error.
I imagine I need to add some setting somewhere that will automatically include React without me needing to explicitly import it at the top of every file. How do I do this? And why does this npm package not do that by default? I know a bit about javascript (and html and css), and have read a bit about React, but I am completely unaware of how npm or webpack works.
Thanks in advance!
EDIT: To clarify, I know how to import stuff with javascript. I can easily add import React from 'react'; to the file and make it work. However, I find it difficult to believe that adding an import statement to every single javascript file is the recommended method, and I don't understand why this example app wouldn't be set up so as to avoid having to do that. Am I mistaken? Do I really need to manually import the same thing over and over again within the same project? Could I set a global variable to React so that I can use it from wherever?
In your default function component you're not extending any classes and just writing a simple function
function App() {
return (
<SomeJSX />
);
}
In class component, you're in fact extending the Class Component by React.Component provided by React default export object and hence you must import it from the package
//only use one of these
import * as React from "react";
import {Component} from "react"; // you can directly extend without writing `React.` with this import
import React from "react"
So your code would be
import React from "react";
class App extends React.Component{
render() {
return (
<TheSameJSX />
);
}
}
Any of the above imports should be fine with a preference to the first and second one.
I've a component loaded using react-loadable (5.4.0) that also loads some other local and external libraries:
import { validationAPI, docstringAPI, autocompleteAPI } from 'utils/request';
import something from './something';
import CodeMirror from 'react-codemirror';
import CM from 'codemirror';
import 'codemirror-docs-addon';
import 'codemirror-docs-addon/lib/main.css';
class MyComponent extends React.Component {
render() {
return (
<div>What I do here it doesn't matter</div>
)
}
}
export default MyComponent
And this is the defined loadable:
import React from 'react';
import Loadable from 'react-loadable';
const Loading = () => (
<div>
Loading stuff
</div>
);
const LoadableComponent = Loadable({
loader: () => import('./MyComponent'),
loading: Loading,
});
export default (props) => (
<LoadableComponent {...props} />
);
The issue I have: if the module I include asynchronously also imports local modules never imported before from my app, I get this error:
Warning: React.createElement: type is invalid -- expected a string
(for built-in components) or a class/function (for composite
components) but got: object.
Check the render method of LoadableComponent.
in LoadableComponent
...
For example: in the code above I have this ./something imported. If this module has never been loaded before in my app I get the error above.
If I:
import the module somewhere else (as for validationAPI, which is imported with no issues)
remove the import
...the app works and I've the async behavior.
Note: If the imported stuff is used or not doesn't matters.
I also tried to move the something module somewhere else, but this seems not related to the module position or to relative import syntax.
Note also that externals libraries does not give me any issues: for example: the codemirror library is included only in that file, but it still works. Only local modules give me the issue.
The only workaround found: not import anything never imported before, but include the something module content inline in the component's file.
This is acceptable but bloat the file size a bit.
I'm not sure this is an issue with react-loadable or webpack or something else.
Any suggestion?
I'm running into the same issue as you... Did you ever figure it out?
I was able to get it to work with Loadable.Map(). But I feel I shouldn't even have to do it this way!
https://github.com/jamiebuilds/react-loadable#loading-multiple-resources
I got this error in my browser
Error in ./src/App.js
Module not found: ./components/todo in C:\Users\James\Desktop\react\src
This is what I got in my editor
import {TodoForm, TodoList} from './components/todo'
http://imgur.com/a/8YLod
I even tried import {TodoForm, TodoList} from './components/todo/' I wonder what's wrong.
Imports work on a per module basis for most loaders/bundlers. In other words, you'll need to import the form and list by doing the following:
import { TodoForm } from './components/todo/TodoForm'
import { TodoList } from './components/todo/TodoList'
As a side note, see https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export to make sure that you're exporting the components correctly. The curly braces around your import works for a named export as opposed to a default export.
In order to just import all files from the directory you must have an index.js file that exports everything from the directory
Which in your case the index.js file would look like this
Export * from 'TodoForm'
Export * from 'TodoList'
Note if the export statement doesn't work see this answer to fix the import / export statement
Do you think, when you wrote import {TodoForm, TodoList} from './components/todo', in TodoForm should be value than you exported from file TodoForm.js, and similarly with TodoList? It's don't works.
You should do import from some file. When you wrote from './components/todo' you tried doing import from todo directory. I guess, in egghead video that import works, because, they have index.js file in todo directory. And in this file they do export for every component separately. Try to add index.js file in todo directory with the following contents:
export * from './TodoForm.js';
export * from './TodoList.js';
it's will work.
So the thing is that when you do
import {TodoForm, TodoList} from './components/todo'
What happends is that your compiler will by default search the components TodoForm and TodoList from the index.js file since you have not mentioned explicitly which files to point to
So if in index.js you add something like
export * from './components/todo/TodoForm';
export * from './components/todo/TodoList';
Your approach will work.
I've been working on a React project and I'm having an issue trying to use ES6 to import several exported React node modules.
This is my code:
I should be able to include the AddFriendInput and FriendList from the hello folder without any issue. But I get this error when webpack/babel compiles:
ERROR in ./src/common/containers/Menu/indexRender.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../../hello in /Users/markpaul/Documents/projects/patient-portal-app/src/common/containers/Menu
# ./src/common/containers/Menu/indexRender.js 122:13-35
The content of my AddFriendInput.js file is like so:
import React, { Component, PropTypes } from 'react';
export default class AddFriendInput extends Component {
constructor(props, context) {
super(props, context);
this.state = {
name: this.props.name || ''
};
}
render() {
return (
<div>
</div>
);
}
}
I use webpack with babel to transpile my files. My Babel config is:
{
"presets": ["react", "es2015", "stage-1"]
}
The only way I can get it to work is to do this:
import AddFriendInput from '../../hello/AddFriendInput/AddFriendInput';
import FriendList from '../../hello/FriendList/FriendList';
But as you can see, this looks horrible.
Can someone please help.
Thanks in advance.
Create home/index.js
import AddFriendInput from './AddFriendInput'
import FriendList from './FriedList'
export { AddFriendInput, FriendList }
OLD ANSWER:
Rename AddFriendInput.js to index.js and after that you can import like this:
import AddFriendInput from '../../hello/AddFriendInput'
ES6 module doesn't automatically load nested directories/files
import by directory name (../../hello) implies that you have hello/index.js
updates
you could just create home/index.js as #Sergey mentioned or there is a module named auto-import that watch your directory and update index.js for you.
I think you are not understand the commonJS.
if the ../../hello is a folder, nodejs will find index.js file. so you must be have a file ../../hello/index.js.
import AddFriendInput from '../../hello/AddFriendInput/AddFriendInput';
import FriendList from '../../hello/FriendList/FriendList';
module.exports = {
AddFriendInput,
FriendList
};
I am unable to import file from parent of project directory. To make things as simple as possible, I created new react-native project and file 'test.js' in a parent directory. I tried to import it with this code:
var Test = require('../test.js');
and
import Test from ('../test.js');
None of these worked - when run in xcode I have following error:
uncaught error Error: UnableToResolveError: Unable to resolve module
../test.js from /Users/UserName/Downloads/TestReact/index.ios.js:
Invalid directory /Users/UserName/Downloads/test.js
Is it possible to import file from parent directory with react-native? I̶ ̶k̶n̶o̶w̶ ̶i̶t̶ ̶w̶o̶r̶k̶s̶ ̶w̶i̶t̶h̶ ̶r̶e̶a̶c̶t̶J̶S̶.
Regards
edit - adding code
test.js
'use strict';
import React, {Component,View,Text} from 'react-native';
class Test extends Component{
render(){
return (
<View>
<Text>
SAMPLE TEXT
</Text>
</View>
);
}
}
module.exports = Test;
index.ios.js
'use strict';
import React, {AppRegistry, View} from 'react-native';
import Test from '../test.js';
var TestReact = React.createClass({
render: function() {
return (
<View><Test/></View>
);
}
});
AppRegistry.registerComponent('TestReact', () => TestReact);
edit - added files hierarchy:
screenshot
edit - actually I was wrong, it's impossible with web react too. When I try to build I got following error:
Module parse failed:
/path_to_file/aaa1.js Line 1:
Unexpected token You may need an appropriate loader to handle this
file type.
So adding react tag to the question.
Try this ./../Component.js. It works for me.
More over if you need access a component from adjacent directory ./../AdjDir/Component.js
This problem may be because react only allows you to import from the src folder. So all resources have to placed in this directory.
Also when you go more than two parent directories back you need to use this syntax:
../../../myfolder/myFile.js
finally a stack overflow question I can answer:
Simply add below jsconfig.json to the base route of your react folder. (Assuming you put all of your react code in "src" folder)
example_react_app
---> public
---> src
---> jsconfig.json
jsconfig.json file content
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"*": ["src/*"]
}
}
}
I looks fine to me . Did you tried with just
import Test from '../test';
instead of
import Test from '../test.js';
And also try without small bracket "( )";
I solved my issue with this. Hope it helps.