React-Native Native Android Module - Toast Example - android

I'm trying to learn to work with android native module and using the toast example in the react-native docs. (https://facebook.github.io/react-native/docs/native-modules-android). However, I am facing an issue where the native module that I was trying to export was unable to be resolved/undefine.
My directory structure is as followed:
example
-android
-app
-src
-main
- java
-com
-example
-CustomToastPackage.java
-ToastModule.java
-MainActivity.java
-MainApplication.java
- res
- AndroidManifest.xml
-ios
-app.js
-index.js
-package.json
My index.js:
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import {NativeModules} from 'react-native';//Added this
module.exports = NativeModules.ToastAndroidTutorial;//Added this
AppRegistry.registerComponent(appName, () => App);
And my App.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import ToastExample from './ToastExample';//Added this
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
ToastExample.show('Awesome', ToastExample.SHORT);//Added this
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.instructions}>To get started, edit App.js</Text>
<Text style={styles.instructions}>{instructions}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
This is the error I am getting.

Based on the code you are showing, this is because you are not correctly importing the Module in your App.js, you should create a file named ToastExample.js in the same directory as App.js and then place
import {NativeModules} from 'react-native';
module.exports = NativeModules.ToastExample;
if in your ToastModule.java you have
#Override
public String getName() {
return "ToastExample";
}
on the getName() method.

Related

undefined is not an object (evaluating 'this.props.navigation.navigate') error in react native

I read the some of the solutions related to this error, but didn't made use of that. Most of them are getting same error because of different reasons. I am kind of beginner to React-Native. So please help me out!
App.js
import loginScreen from './components/Login';
import React from 'react'
import {createStackNavigator} from 'react-navigation-stack';
import {createAppContainer} from 'react-navigation';
import homeScreen from "./HomeScreen";
import LoadingScreen from "./components/LoadingScreen";
import SignUpScreen from "./components/SignUpScreen";
import StarterScreen from "./components/starter";
import ShoppingCartIconScreen from './components/ShoppingCartIcon';
import SummeryScreen from './components/summery'
const MainNavigator=createStackNavigator(
{
signup:{screen:SignUpScreen},
login:{screen:loginScreen},
Loading: {screen: LoadingScreen },
Summery:{screen:SummeryScreen}, //exporting the Summery component
Starter:{screen:StarterScreen,
navigationOptions:{
title:'Starters',
headerRight:<ShoppingCartIconScreen/>,//using as a icon on the navigation header.
headerStyle:{
backgroundColor:'#694fad'
},
headerTitleStyle:{
color:'white'
}
}},
Home: { screen: homeScreen,
navigationOptions:{
headerTitle:'Home',
headerRight:<ShoppingCartIconScreen/>,
headerStyle:{
backgroundColor:'#694fad',
},
headerTitleStyle:{
color:'white'
}
}}
},
{
initialRouteName:"Home" //set home as a default screen
}
);
const App=createAppContainer(MainNavigator);
export default App; //exporting App.js with stack navigator
ShoppingCartIcon.js
import React from 'react';
import {View,Text,StyleSheet,Platform} from 'react-native';
import Icon from '#expo/vector-icons/Ionicons'
//creating a constant
const ShoppingCartIcon = (props) => (
<View style={[{ padding: 5 }, Platform.OS == 'android' ? styles.iconContainer : null]}>
<View style={{
position: 'absolute', height: 20, width: 20, borderRadius: 15, backgroundColor: '#e3e3e3', right: 6, bottom: 29, alignItems: 'center', justifyContent: 'center', zIndex: 2500,
}}>
<Text style={{ color: 'black', fontWeight: 'bold' }}>0</Text>
</View>
<View style={{top:3}}>
<Icon onPress={()=>props.navigation.navigate("Summery")} name="ios-cart" size={35} color='yellow' /> //navigate to summery screen on icon press
</View>
</View>
)
export default ShoppingCartIcon; //exporting shoppingcarticon
Summery.js
//just a dummy file
import React from 'react'
import {View,Text,StyleSheet} from 'react-native'
//nothing special here
export default class summery extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>summery page</Text>
</View>
)
}
}
this.props.navigation is only available in Components that are directly assigned as screens in a navigator, such as the stack navigator generated by createStackNavigator.
If you want access to navigation outside of those Components, either directly pass the navigation prop (which I would not recommend), or follow this tutorial to navigate without the navigation prop: https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
Well, I think your error is because you didn't add ShoppingCartIcon as part of your StackNavigator, for this reason, you cannot query navigator properties from props. What you can do is pass navigator properties of App through props of ShoppingCartIcon, I mean you should write something like this
// App.js
import LoginScreen from './components/Login';
import React from 'react'
import {createStackNavigator} from 'react-navigation-stack';
import {createAppContainer} from 'react-navigation';
import HomeScreen from "./HomeScreen";
import LoadingScreen from "./components/LoadingScreen";
import SignUpScreen from "./components/SignUpScreen";
import StarterScreen from "./components/starter";
import ShoppingCartIconScreen from './components/ShoppingCartIcon';
import SummeryScreen from './components/summery'
const MainNavigator=createStackNavigator(
{
Signup:SignUpScreen,
Login:LoginScreen, //Name of components have to start with Uppercase Letter
Loading: LoadingScreen,
Summery: SummeryScreen, //exporting the Summery component
Starter:StarterScreen,
Home: HomeScreen,
},
{
initialRouteName:"Home" //set home as a default screen
}
);
const AppContainer=createAppContainer(MainNavigator);
class App extends React.Component{
constructor(props){
super(props)
}
render(){
return(
<AppContainer/>
)
}
}
export default App; //exporting App.js with stack navigator
//ShoppingCartIcon.js
import React from 'react';
import {View,Text,StyleSheet,Platform} from 'react-native';
import Icon from '#expo/vector-icons/Ionicons'
//creating a constant
const ShoppingCartIcon = (navigation) => (
<View style={[{ padding: 5 }, Platform.OS == 'android' ? styles.iconContainer : null]}>
<View style={{
position: 'absolute', height: 20, width: 20, borderRadius: 15, backgroundColor: '#e3e3e3', right: 6, bottom: 29, alignItems: 'center', justifyContent: 'center', zIndex: 2500,
}}>
<Text style={{ color: 'black', fontWeight: 'bold' }}>0</Text>
</View>
<View style={{top:3}}>
<Icon onPress={()=> navigation.navigate("Summery")} name="ios-cart" size={35} color='yellow' /> //navigate to summery screen on icon press
</View>
</View>
)
export default ShoppingCartIcon; //exporting shoppingcarticon
//Home.js or Starter.js
class Name extends React.Component{
//Add this
static navigationOptions = ({ navigation }) => { //Configuración de pantalla
return {
title:'Name',
headerRight:(<ShoppingCartIconScreen navigation = {navigation}/>),//using as a icon on the navigation header.
headerStyle:{
backgroundColor:'#694fad'
},
headerTitleStyle:{
color:'white'
}
};
};
}
It´s a better approach to define navigationOptions for every single screen in this case. Just like I describe on the code above.
Furthermore, I advise to use this approach to define react components :
class App extends React.Component{
constructor(props){
super(props)
}
//Some functions ...
render(){ return(//.... what you want)}
I hope this helps you :)

Unable to resolve image path from login.js

I'm totally new to expo and react native
I'm trying to use ImageBackground
I use it as the code below but I get this error "Unable to resolve "./assets/back.jpg" from "app\components\Login.js" "
My image is already in assets folder in my project
And also when I try to import font I get the same error
Does it need to import something before using or something else?
I also Tried it by not importing the image and adding the path directly to source property
Login.js
import React, { Component } from 'react';
import back from './assets/back.jpg';
import {
StyleSheet,
Text,
View,
TextInput,
KeyboardAvoidingView,
TouchableOpacity,
AsyncStorage,
Image,
ImageBackground,
} from 'react-native';
import {createStackNavigator, createAppContainer} from 'react-navigation';
export default class Login extends React.Component {
static navigationOptions = {
header: null,
};
constructor(props) {
super(props);
this.state = {
username:'',
password:'',
}
}
componentDidMount(){
this._loadInitialState().done();
}
_loadInitialState = async () =>{
var value = await AsyncStorage.getItem('user');
if (value !=null){
this.prop.navigation.navigate('Profile');
}
}
render() {
return (
<ImageBackground source={back} style={styles.backImg}>
<KeyboardAvoidingView behavior='padding' style={styles.wrapper}>
<View style={styles.container}>
<Image
style={styles.logo}
source={require('/MyFirst/assets/logo.png')}
/>
<TextInput
style={styles.textInput} placeholder='Username'
onChangeText={(username) =>this.setState({username}) }
underlineColorAndroid = 'transparent'
/>
<TextInput
style={styles.textInput} placeholder='Password'
onChangeText={(password) =>this.setState({password}) }
underlineColorAndroid = 'transparent'
/>
<TouchableOpacity style={styles.btn}
onPress={this.login}>
<Text style={styles.btnText}>Login</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
wrapper:{
flex:1,
},
container:{
flex:1,
alignItems:'center',
justifyContent:'center',
backgroundColor:'#e5ffd3',
paddingLeft:40,
paddingRight:40,
},
logo:{
width: 250,
height: 250,
},
textInput:{
alignSelf:'stretch',
padding:16,
marginBottom:20,
backgroundColor:'#fff',
borderWidth: 1,
borderColor: '#d6d7da',
borderRadius: 25,
},
btn:{
alignSelf:'stretch',
backgroundColor:'#589e25',
padding:20,
alignItems: 'center',
borderRadius: 25,
},
btnText:{
color: '#ffffff',
},
})
App.js
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
import {createStackNavigator, createAppContainer} from 'react-navigation';
import Login from './app/components/Login'
import Profile from './app/components/Profile'
const MainNavigator = createStackNavigator({
Home: {screen: Login},
Profile: {screen: Profile},
});
const App = createAppContainer(MainNavigator);
export default App;
You should use ImageBackground in this way. It will solve your problem
<ImageBackground source={require('../../assets/back.jpg')} style={styles.backImg}>
Working example can be found here Link

my app js not working in react native. what my mistake?

I newbie for react native. when I learning to hello world in app.js. when I run for android "native-react run-android" build success but not working on my phone. not change
this is my code in app.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Hello, Steven Wiaji, S.Kom</Text>
<Text style={styles.instructions}>To get started, edit App.js</Text>
<Text style={styles.instructions}>{instructions}</Text>
</View>
);
}}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
this is adb running
this is when i run on my phone
There's nothing wrong with the code. Probably issue with node_modules. You might wanna delete the folder and do a npm i or yarn again.
Here's a working example.
https://snack.expo.io/S1oozjjUV

cant import component react native

So I'm new to react native and I am following this tutorial video, and I can't seem to be able to import the 'Splash' component.
This is the error message I get
Error Message
And this is the code I have written
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
Image,
TextInput,
} from 'react-native';
import Splash from './splash';
export default class App extends Component<{}> {
render() {
return (
<Splash/>
);
}
}
And the component I want to import
import React, { Component } from 'react';
import { View, Text } from 'react-native';
export default class Splash extends Component {
render() {
return(
<View style={styles.wrapper}>
<View style={styles.titleWrapper}>
<Text style={styles.title}>Hello World!</Text>
</View>
<View>
<Text style={styles.subtitle}>Powered by React
Native</Text>
</View>
</View>
);
}
}
const styles = Stylesheet.create({
wrapper: {
backgroundColor: 'red',
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
title: {
color: 'white',
fontSize: 35,
fontWeight: 'bold',
},
subtitle: {
color: 'white',
fontWeight: '200',
paddingBottom: 20
},
titleWrapper: {
justifyContent: 'center',
flex: 1
}
});
Any help would be greatly appreciated.
There are 2 solutions you can do.
1) Have you tried re-running your emulator. Sometimes you just need to rerun the emulator again as it does not pick up your files during first run.
2) import Spalsh from './Splash you need to capitalize your Splash
3) Check your file path to splash. Its most likely incorrect.

Application main thread has not been registered in react native

Hi I am new in react native programming, I am trying to make first program in it. I am facing below issue :-
import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';
class HelloWorldApp extends Component {
render() {
return (
<Text>Hello world!</Text>
);
}
}
AppRegistry.registerComponent('HelloWorldApp', () => HelloWorldApp);
Edit
I am using this tool https://rnplay.org
When you are using rnplay, You need to call
registerComponent(HelloWorldApp);
instead of
AppRegistry.registerComponent('HelloWorldApp', () => HelloWorldApp);
Sample Hello world example
import React from 'react';
import {
registerComponent,
} from 'react-native-playground';
import {
StyleSheet,
Text,
View,
} from 'react-native';
class HelloWorldApp extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.instructions}>
Hello world
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
instructions: {
fontSize: 16,
textAlign: 'center',
margin: 15,
},
});
registerComponent(HelloWorldApp);

Categories

Resources