I have been trying to get my head around React Native as I recently took the decision to switch to it from Cordova.
I have been trying to understand how container and component files should be properly structured inside src in order to correctly build.
To this end I have been attempting to run the initial index.android.js code out of a new file "app.js" which I have created in a folder I called js found in the original /src/main folder.
This is the index file code
/*Both index files index.ios.js and index.android.js MUST be indentical*/
var React= require('react-native');
var { AppRegistry } = React;
var App = require('./android/app/src/main/js/app.js')
AppRegistry.registerComponent('LearnD', () => LearnD);
And the app.js file can be found at this gist here.
I have been then receiving the following error:
Any help will be more than appreciated.
Thanks in advance,
Jake.
A typical setup for a React Native application looks something like:
└── YourApp
├── android # Native Android files, no .js here
├── index.android.js # Android entry point, must exist
├── index.ios.js # iOS entry point, must exist
├── ios # Native iOS files, no .js here
└── src # All your .js sources
├── components # All your .js sources
└── main.js # Your shared entry point
Your src/main.js can then export a single, shared entry point component for both platforms and uses other components inside the src/ directory:
// src/main.js
import React, { Component } from 'react';
import { View } from 'react-native';
import OtherComponent from './components/other-component.js'
// note export default
export default class Main extends Component {
render() {
return (
<View>
<OtherComponent />
</View>
);
}
}
And your index.ios.js and index.android.js components can import and register the main component as the application root component:
// index.ios.js and index.android.js
// both must exist, but they can be identical
import { AppRegistry } from 'react-native';
import Main from './src/main';
AppRegistry.registerComponent('YourApp', () => Main);
Within the src directory, you can then structure your app code in any way you best see fit, e.g. src/components and src/containers - entirely up to you!
Your file is trying to export App on line 48, which does not exist. You already have export default class LearnD on line 10, so omit line 48 and that should help
Related
I did add the folder structure so you could see.
How am I able to import image component into the card component ? Doesn't matter what path I try I get this error
./src/Components/Card/Card.js
Module not found: Can't resolve '../../Components/Image' in
'/Users/user/project/projecttest/src/Components/Card'
import React from 'react'
import styled, {ThemeProvider, css } from 'styled-components'
import Image from '../../Components/Image'
No, I see you importing: import Image from '../../Components/Image'. This mean you importing index of Image folder.
But in your code, you defining Image.js not index.js.
So, you have to import like this:
import Image from '../Image/Image'
Or, you can rename file Image.js to index.js to shorten the code when import:
// rename Image.js to index.js
// then, import file:
import Image from '../Image'
You should write Image at the end or change filename to index.js
import Image from '../../Components/Image/Image'
Try absolute imports in react. create a .env file in your root directory. contents of the file
NODE_PATH=src
#Jikun L answer is correct. I'm wondering why is it not in image format.
Perhaps Change the Folder Structure to this:
Components
-- Card
-- -- > index.js
-- -- > styles.js
-- Image
-- -- > xxx.png
-- -- > package.json
Package.json:
{
"name": "#image"
}
In Card (index.js)
<Image
source={require("#images/xxx.png")}
/>
I'm trying to mock my import with animations, but I keep getting
● Test suite failed to run
C:\work\portfolio\node_modules\gsap\TweenMax.js:13
import TweenLite, { TweenPlugin, Ease, Power0, Power1, Power2, Power3, Power4, Linear } from "./TweenLite.js";
^^^^^^^^^
SyntaxError: Unexpected identifier
The error is from one of the imports from my file.
App.js
const App = () => (
<ChronologyGraph
width="700"
height="800"
nodeSize={10}
milestones={milestones.reverse()}
columns={nodeTypes}
/>
);
export default App;
inside of ChronologyGraph I import my component ProjectNode which imports another file I made animation.js and inside of animation.js I import
import { TimelineMax, Power0 } from "gsap/TweenMax";
import { TweenMax } from "gsap/TweenMaxBase";
Which are causing the error above, I want to either mock this gsap library or just my animation.js
App.test.js
import React from "react";
import { shallow } from 'enzyme';
import App from "./App";
fit("renders without crashing", () => {
jest.mock('../animation.js');
jest.mock('gsap/TweenMaxBase');
jest.mock('gsap/TweenMax');
const wrapper = shallow(<App />);
});
And here are all the mocks I've tried without any success
Coming late to this, but sharing because the solution is very simple. (I've already answered here as well)
If you read Jest documentation you can simply mock GSAP creating a file in __mocks__ directory.
Mocking TweenMax
Let's say you are importing TweenMax and you want to use to method:
import { TweenMax } from "gsap/TweenMax";
Add two files into the mocks directory. TweenLite can be empty.
.
└── __mocks__
└── gsap
└── TweenMax.js
└── TweenLite.js
module.exports = {
TweenMax: class{
static to(selector, time, options) {
return jest.fn();
}
}
}
You've successfully mock your TweenMax.to method.
Mocking TimelineMax
Because TimelineMax works on instances of a class the mock should be done this way:
import { TimelineMax } from "gsap/TimelineMax";
Again, add two files into the mocks directory. TweenLite can be empty.
.
└── __mocks__
└── gsap
└── TweenLite.js
└── TimelineMax.js
module.exports = {
TimelineMax: class {
constructor(){
this.to = jest.fn().mockReturnThis();
}
}
};
Use mockReturnThis() to be able to chain methods.
You could try using the UMD version instead, like:
import TweenLite from "gsap/umd/TweenLite"
please update your jest config:
"transform": {
"\\.js$": "<rootDir>/node_modules/babel-jest"
}
and install babel-jest.
Further if your issue wouldn't get resolved then share your jest config and we don't usually mock imports.
I've been having an issue with importing a react class into a container
My file organization is as follows:
├── components
│ ├── Header
│ │ ├── Header.js
│ │ └── index.js
│ └── index.js
├── containers
│ └── HeaderContainer.js
└── index.js
where components/Header/Header.js exports with
export default class Header extends Component {}
components/Header/index.js is
import Header from './Header';
import './Header.scss';
export default Header;
and components/index.js is
export Header from './Header';
and containers/HeaderContainer.js is trying to import with
import { Header } from '../components';
However, this doesn't work, Header is undefined.
If I use import * as components from '../components';,
Header is listed, but using components.Header is again undefined.
However, it works perfectly if I instead do
import Header from '../components/Header';
Can anyone explain why the first two methods don't seem to be working? I've done it before this way, and I cannot figure out what I may have changed (admittedly, part of the reason I'm asking is just to type it out a new way and seeing if it helps)
Additionally, I've been able to use
import { Header } from './components';
from an index file in the main directory, which worked perfectly. The issue seems to somehow be with import { Header } from '../components' only
You probably have a cyclical dependency issue. Consider:
components/index.js starts loading.
It sees it needs containers/HeaderContainer.js, so it suspends.
containers/HeaderContainer.js starts loading.
It sees it needs import { Header } from '../components';, so it suspends.
components/index.js is already loading from step 1, so this step is a no-op.
containers/HeaderContainer.js starts running again.
Since components/index.js is still loading, the imported Header is pointing to a variable that hasn't been initialized yet, like if you did
console.log(Header);
let Header = ...
Babel's behavior in this situation is to make Header undefined. In a real native ES6 module environment, it would throw an exception because Header wasn't initialized yet.
There are two main options to fix this. Either one should help:
Import ../components/Header directly to avoid the already-loading components/index.js.
Reorder your imports so Header is already initialized in components. e.g.
export { HeaderContainer } from './containers/HeaderContainer';
export { Header } from './Header';
to
export { Header } from './Header';
export { HeaderContainer } from './containers/HeaderContainer';
There are two types of export: named and default.
Named export should be consumed by using construct like:
import { Header } from '../components';
Default on the other hand should be consumed like:
import Header from '../components';
You can read more here;
Because the only thing you can omit from the path is index.js
So if you have
import Header from '../components/Header';
It is the same as
import Header from '../components/Header/index.js';
But if you type
import { Header } from '../components';
Interpreter expects that in the file ../components/index.js or it could be just ../components.js if components is a file and not a folder, it will find a named export
export const Header = () => {...}
More about exports
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 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.