React native: Component not defined? Can't import? - javascript

Ok, very new to react native here and Im trying to very simply import another .js file and have that be run in the main render() func in index.ios.js
I have looked everywhere and tried both import and require to do this, however I am stuck with error:
Here is what I have, the error is thrown at just the addition of the import line:
import React, { Component } from 'react';
import { Button, Card } from 'react-native-material-design';
import {
StyleSheet,
Text,
View,
Animated,
Easing,
ScrollView,
RefreshControl,
AppRegistry
} from 'react-native';
//import { Container, Content } from 'native-base';
import TestClass from "./TestClass";
//var animation = require('./TestClass');
//BODY
export default class SkysReact extends Component {
render() {
return (<View style={styles.container}>
<TestClass/>
</View>);
// return (<View style={styles.container}>
// {this.test()}
// </View>);
}
test() {
console.log("Hello World")
}
animate()
{
console.log("animate");
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#404040',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: '#333333'
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('SkysReact', () => SkysReact);
And my other class:
import React from 'react';
import Animation from 'lottie-react-native';
import {
StyleSheet,
Text,
View,
Animated,
Easing,
ScrollView,
RefreshControl,
AppRegistry
} from 'react-native';
export default class TestClass extends Component { // not defined error here
render() {
return (<View style={styles.container}>
{this.test()}
</View>);
}
test() {
console.log("Hello World 2222")
}
}
module.exports = TestClass;
How can I just display TestClass in my index.ios.js? What is wrong?

Ah hah. I know exactly what it is. Compare the very top line of your TestClass file with mine below. You will see the difference. Fix this, and your done.
import React, {Component} from 'react';
import Animation from 'lottie-react-native';
import {
StyleSheet,
Text,
View,
Animated,
Easing,
ScrollView,
RefreshControl,
AppRegistry
} from 'react-native';
export default class TestClass extends Component {
render() {
return (<View style={styles.container}>
{this.test()}
</View>);
}
test() {
console.log("Hello World 2222")
}
}
You were missing the, {Component} in your import statement. I also took our your module.exports statement, its unnecessary.

this.test() is not a valid child of your <View> in TestClass because it is not a valid React Component, nor does it return one.
If you want to "test" that your TestClass.render() function is running, put the console.log() above your return statement, like this:
render() {
this.test();
return (
<View style={styles.container}></View>
);
}
Of course, you won't actually see anything because TestClass doesn't have any children.

Related

It doesn't recognize a file within an imported file

I have created a MenuButton as well as 2 other pages one of them being the settingScreen, where I have imported the MenuButton within both files and they seem to be working fine. But when I import the setting Screen on the DrawerNavigator file it doesn't recognize MenuButton
Failed to load bundle(http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false) with error:(Unable to resolve module `./Menu/MenuButton` from `/Users/camillebasbous/Project/Menu/SettingScreen.js`: The module `./Menu/MenuButton` could not be found from `/Users/camillebasbous/Project/Menu/SettingScreen.js`. Indeed, none of these files exist:
* `/Users/camillebasbous/Project/Menu/Menu/MenuButton(.native||.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)`
* `/Users/camillebasbous/Project/Menu/Menu/MenuButton/index(.native||.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)` (null))
__38-[RCTCxxBridge loadSource:onProgress:]_block_invoke.228
RCTCxxBridge.mm:414
___ZL36attemptAsynchronousLoadOfBundleAtURLP5NSURLU13block_pointerFvP18RCTLoadingProgressEU13block_pointerFvP7NSErrorP9RCTSourceE_block_invoke.118
__80-[RCTMultipartDataTask URLSession:streamTask:didBecomeInputStream:outputStream:]_block_invoke
-[RCTMultipartStreamReader emitChunk:headers:callback:done:]
-[RCTMultipartStreamReader readAllPartsWithCompletionCallback:progressCallback:]
-[RCTMultipartDataTask URLSession:streamTask:didBecomeInputStream:outputStream:]
__88-[NSURLSession delegate_streamTask:didBecomeInputStream:outputStream:completionHandler:]_block_invoke
__NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__
-[NSBlockOperation main]
-[__NSOperationInternal _start:]
__NSOQSchedule_f
_dispatch_call_block_and_release
_dispatch_client_callout
_dispatch_continuation_pop
_dispatch_async_redirect_invoke
_dispatch_root_queue_drain
_dispatch_worker_thread2
_pthread_wqthread
start_wqthread
I have tried testing ou the other page and after a few tests I realized that the presence of the imported MenuButton within these pages is what is forcing an error Is there a way to import a file that has imported another to be displayed or do I have to import both of them within drawerNavigation and if so how to structure the code. Thanks
Drawer Navigation code:
import * as React from 'react';
import { Text, View, Image, ScrollView, StyleSheet } from 'react-native';
import {
createDrawerNavigator,
createAppContainer,
DrawerItems,
SafeAreaView,
} from 'react-navigation';
import SettingScreen from './Menu/SettingScreen'
class Home extends React.Component {
static navigationOptions = {
title: 'Home',
};
render() {
return (
<View style={styles.container}>
<SettingScreen/>
</View>
);
}
}
const Navigator = createDrawerNavigator(
{
Home,
},
{
//drawerType: 'back',
// drawerPosition: 'right',
// drawerWidth: 200,
drawerBackgroundColor: '#262A2C',
// contentComponent: CustomDrawerContentComponent
}
);
export default createAppContainer(Navigator);
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
}
});
SettingScreen code:
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import MenuButton from './Menu/MenuButton'
export default class SettingScreen extends React.Component{
render(){
return(
<View style={styles.container}>
<MenuButton/>
<Text style={styles.text}>Settings</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'rgba(215,215,215,1)',
alignItems: 'center',
justifyContent: 'center',
},
text:{
fontSize: 30,
}
});
MenuButton code:
import React from 'react';
import {AppRegistry, StyleSheet, View} from "react-native" ;
import Icon from 'react-native-vector-icons/Ionicons'
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen'
export default class MenuButton extends React.Component {
render() {
return(
<View >
<Icon name= "ios-menu" size={wp('12%')} color='#9B9B9B' style={{position: 'absolute', top: wp('-82.5%'), left: wp('-46%'), }}></Icon>
</View>
)
}
}
AppRegistry.registerComponent('Menu', () => FixedDimensionsBasics);
The path you are using on import is relative to your file. So, as everything is on the same folder, you must correct the import path like that:
On Drawer Navigator code
import SettingScreen from './SettingScreen'
On SettingScreen code
import MenuButton from './MenuButton'

How to properly import screens in the same directory?

I'm new to react-native/expo, and I'm currently trying to test my code and make sure that I set up react-navigation properly. When I try to run on expo on my smartphone, I get back this:
Unable to resolve module './screens/RegistrationScreen' from
'C:\Users[username]\Desktop\JDA\Smartbox\screens\HomeScreen.js': The
module './screens/RegistrationScreen could not be found from
'C:\Users[username]\Desktop\JDA\Smartbox\screens\HomeScreen.js'.
Indeed, none of these files exist...
I'm not exactly sure if I'm writing the directory wrong or not, but I can't seem to find many other situations where this is happening and find a proper solution.
import React from 'react';
import {
Image,
Platform,
ScrollView,
StyleSheet,
StatusBar,
Text,
Button,
TouchableOpacity,
View,
} from 'react-native';
import { WebBrowser } from 'expo';
import { MonoText } from '../components/StyledText';
import {createStackNavigator} from 'react-navigation';
import RegistrationScreen from './screens/RegistrationScreen';
export default class HomeScreen extends React.Component {
static navigationOptions = {
header: null,
};
onPress = () => {
this.props.navigation.navigate('Home')
};
render() {
return (
<View style={{flex: 1}}>
<View style={[{flex: 1}, styles.container]}>
<Text style={styles.getStartedText}>Manage my locks</Text>
</View>
<View style={{flex: 2}}/>
<Button style={{flex: 1}}title="Registration Test" onPress={this.onPress}>
</Button>
<Button style={{flex: 1}} title="Add new lock">
</Button>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
...Platform.select({
android: {
marginTop: StatusBar.currentHeight + 15
}
})
},
developmentModeText: {
marginBottom: 20,
color: 'rgba(0,0,0,0.4)',
fontSize: 14,
lineHeight: 19,
textAlign: 'center',
},
contentContainer: {
paddingTop: 30,
}
});
createStackNavigator({
Register: {
screen: RegistrationScreen
},
Home: {
screen: HomeScreen
}
});
The header from RegistrationScreen is like so:
import React from 'react';
import {
AppRegistry,
Button,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native';
import {createStackNavigator} from 'react-navigation';
import HomeScreen from './screens/HomeScreen';
The HomeScreen and Registration Screen are in the same directory. I'm just doing this for testing, but I want to be sure that I can navigate from this screen to registration once I press the button.
Since your HomeScreen and RegistrationScreen are in same directory your import of HomeScreen should be
import HomeScreen from './HomeScreen';
instead of
import HomeScreen from './screens/HomeScreen';
and of RegistrationScreen should be
import RegistrationScreen from './RegistrationScreen';
instead of
import RegistrationScreen from './screens/RegistrationScreen';

Fix Error: The component for route 'Home' must be a React component

I'm trying to used react-navigation but I can not get it to work when I move each screens' components into multiple files. I always get this error: "The component for route 'Home' must be a React component". This error doesn't happen if I move all of the code into one file, so I'm not sure what the difference is.
Here is my App.js:
import React from 'react';
import { StackNavigator } from 'react-navigation';
import { AppRegistry, StyleSheet, Text, View, TouchableHighlight } from 'react-native';
import { HomeScreen } from './screens/HomeScreen';
import { JoinScreen from './screens/JoinScreen';
import { HostScreen } from './screens/HostScreen';
const Root = StackNavigator(
{
Home: {
screen: HomeScreen,
},
Details: {
screen: JoinScreen,
}
},
{
initialRouteName: 'Home',
headerMode: 'none',
}
);
export default class App extends React.Component {
render() {
return (
<Root />
)
}
}
And here is my .screens/HomeScreen.js
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class HomeScreen extends React.Component {
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<Text style={styles.title}>Hello World</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'space-around',
}
});
I think that if you change this line:
import { HomeScreen } from './screens/HomeScreen';
to:
import HomeScreen from './screens/HomeScreen';
(i.e. removing the braces around HomeScreen) then it will work. Because you used export default in the HomeScreen component's source file, you don't need the destructuring on the import. This is attempting to access a variable called HomeScreen on the component, which is resolving to undefined and causes the error you saw.
Alternatively, you can remove the default from export default and keep the import the same. I personally prefer removing the braces as the code looks cleaner.
There's also a missing closing brace on this line:
import { JoinScreen from './screens/JoinScreen';
But I assumed that was a typo ;)
I think that react is having a problem figuring out what to import
Since you're exporting one thing by default
You should replace import { HomeScreen } from './screens/HomeScreen';
with
import HomeScreen from './screens/HomeScreen';
Try with:
Home: {
screen: () => <HomeScreen/>,
},
It also happens if you do not export your class.
export default class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('Details')}
/>
</View>
);
}
}
Add this to your js file at the bottom add this Line
export default MainActivity;
import React, { Component } from 'react';
import { createStackNavigator } from 'react-navigation-stack';
class MainActivity extends Component{
...
}
export default MainActivity;
Since you've mentioned the default, I think that if you change this line:
import { HomeScreen } from './screens/HomeScreen';
to:
import HomeScreen from './screens/HomeScreen';
This would solve the issue. Cheers mate!
Keep the braces intact for your external screen files imports. Just do the following and it should run on both Android and iOS simulators regardless
// HomeScreen.js
... all imports
export class HomeScreen extends React.Component {
...
This fixed the issue for me in both platforms.
I was using "react" instead of 'react'. I removed the double quotes from react and the error gone away.

React Native throws ' 6 stack frames were collapsed.' error

This is the entire code
class App extends React.Component {
render() {
return (
<div className="container">
<Nav />
</div>
);
}
}
const styles = StyleSheet.create({
topnav: {
position : 'fixed',
top : 0,
right : 0
}
});
ReactDOM.render(<App />, document.getElementById('app'));
Why does this error occur? Should import anything to support 'StyleSheet'?
You have to use this import for the Style sheet:
import { StyleSheet } from 'react-native';
But another problem is that you are using a div. Div's are not available in React-Native, so you have to use other elements (like views).
Example:
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class App extends React.Component {
render() {
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
});
return <View style={styles}><Text>I'm a Text</Text></View>;
}
}

Exported Constant not working in stylesheet

In one of the components in my project, I export a constant integer and then use it as a value for height in StyleSheet. In one particular case, it is not working and I can't figure out why. I have extracted the minimum possible code to reproduce it.
In TopBar.js, I export NAVBAR_HEIGHT and import it in both Home.js and MyModal.js. While it works right in Home.js when I use it as value of height in StyeSheet, it doesn't work in MyModal.js. However, if I replace NAVBAR_HEIGHT with a hardcoded int value, it works. It also works if I use NAVBAR_HEIGHT inline instead of creating a StyleSheet and passing the styles.topbar object.
(I wanted to make an rnplay for this, but looks like it can't make multiple files and thus, I couldn't reproduce it.)
Here is the code, apologies for making it long. I've also pushed it to git here.
Home.js (root component)
import React from 'react';
import {
View, StyleSheet, TouchableHighlight
} from 'react-native';
import TopBar, { NAVBAR_HEIGHT } from './TopBar';
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = { showModal: false };
}
render() {
return (
<TouchableHighlight onPress={this.toggleModal}>
<View style={styles.view}>
<TopBar showModal={this.state.showModal}
onClose={this.toggleModal} />
</View>
</TouchableHighlight>
);
}
toggleModal = () => {
this.setState({ showModal: !this.state.showModal });
}
}
const styles = StyleSheet.create({
view: {
height: NAVBAR_HEIGHT,
backgroundColor: 'blue',
}
});
MyModal.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Modal,
Text,
} from 'react-native';
import { NAVBAR_HEIGHT } from './TopBar';
export default class MyModal extends Component {
render() {
return (
<Modal animationType={'slide'}
visible={this.props.visible}
style={styles.container}
onRequestClose={this.props.onClose}>
<View style={styles.topbar}>
<Text style={styles.text}>{NAVBAR_HEIGHT}</Text>
</View>
</Modal>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
topbar: {
backgroundColor: 'red',
height: NAVBAR_HEIGHT,
},
text: {
fontSize: 20
}
});
TopBar.js
import React, { Component } from 'react';
import {
View,
StyleSheet,
Platform,
Text,
} from 'react-native';
import MyModal from './MyModal';
export const NAVBAR_HEIGHT = Platform.OS === 'ios' ? 200 : 100;
export default class TopBar extends Component {
render() {
return (
<View style={styles.container}>
<Text>TEST</Text>
<MyModal visible={this.props.showModal}
onClose={this.props.onClose} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'green',
},
});
I might be making some silly mistake but I have spent way too much time on this one and I'm still clueless. Help.
The modules TopBar.js and MyModal.js have a circular dependency: TopBar imports MyModal, and MyModal imports TopBar. Because module resolution is synchronous, the imported value is undefined.
Extract the common dependency into its own module and reference it from both TopBar and MyModal.
Here's a simple reproduction:
a.js
import {b} from './b';
export const a = 'a';
console.log('A sees B as', b);
b.js
import {a} from './a';
export const b = 'b';
console.log('B sees A as', a);
main.js
import {a} from './a';
Outputs:
B sees A as undefined
A sees B as b

Categories