react-native router flux Actions is not navigating to other page - react-native

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
Image,
Button
} from 'react-native';
import Actions from 'react-native-router-flux';
import First from './First';
export default class Home extends Component{
componentWillMount() {
}
render(){
return(
<View>
<View style={{height:220,backgroundColor:'#DCDCDC'}}>
<Image style={{width:120,height:120,top:50,left:120,backgroundColor:'red'}}
source={require('./download.png')} />
</View>
<View style={{top:30}}>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<TouchableOpacity style= { styles.views}
onPress = {()=>{ Actions.First({customData: 'Hello!'}) }}>
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> Profile </Text>
</TouchableOpacity>
<TouchableOpacity style= { styles.views1} >
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> Health Tracker </Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
In the above code, Actions in not working means not navigating to First.js page, how can i edit my code, and i have not written anything in ComponentWillMount() function, what i should write inside that?ataomega
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity
} from 'react-native';
import Home from './Home';
export default class Prof extends Component{
constructor(){
super()
}
render(){
return (
<Navigator
initialRoute = {{ name: 'Home', title: 'Home' }}
renderScene = { this.renderScene }
navigationBar = {
<Navigator.NavigationBar
style = { styles.navigationBar }
routeMapper = { NavigationBarRouteMapper } />
}
/>
);
}
renderScene(route, navigator) {
if(route.name == 'Home') {
return (
<Home
navigator = {navigator}
{...route.passProps}
/>
)
}
}
}
var NavigationBarRouteMapper = {
LeftButton(route, navigator, index, navState) {
if(index > 0) {
return (
<View>
<TouchableOpacity
onPress = {() => { if (index > 0) { navigator.pop() } }}>
<Text style={ styles.leftButton }>
Back
</Text>
</TouchableOpacity>
</View>
)
}
else { return null }
},
RightButton(route, navigator, index, navState) {
if (route.openMenu) return (
<TouchableOpacity
onPress = { () => route.openMenu() }>
<Text style = { styles.rightButton }>
{ route.rightText || 'Menu' }
</Text>
</TouchableOpacity>
)
},
Title(route, navigator, index, navState) {
return (
<Text style = { styles.title }>
{route.title}
</Text>
)
}
};

First of all I recommend you to create a rounter component and make your app launch from there:
Something like this
import { Scene, Router, ActionConst } from 'react-native-router-flux';
import First from 'yourRoute';
const RouterComponent = () => {
<Router>
<Scene
key="First"
component={First}
initial />
... your other scenes
</Router>
}
export default RouterComponent;
then in your index page or wherever you load from just add this component
import React, { Component } from 'react'
import RouterComponent from './Router'
class AppContainer extends Component {
render() {
return (
<RouterComponent />
);
}
}
export default AppContainer;
now you can call it from your code. Any doubts ask them :P

Related

React Native => Invariant violation on redux-saga migration

I am getting the below issue when I started to configure with Redux sagas in React native application:
App.js:
import React from 'react';
import AppNavigator from './config/AppNavigator'
import { Provider as PaperProvider } from 'react-native-paper';
import * as Font from 'expo-font'
import { createStore } from 'redux'
import { Provider as ReduxProvider} from 'react-redux'
import InitialReducer from './reducer/Initial-reducer'
const store = createStore(InitialReducer)
export default class App extends React.Component {
componentDidMount() {
Font.loadAsync({
'RobotoBlack': require('./assets/fonts/Roboto/Roboto-Black.ttf'),
'RobotoBold': require('./assets/fonts/Roboto/Roboto-Bold.ttf'),
'RobotoRegular': require('./assets/fonts/Roboto/Roboto-Regular.ttf'),
});
}
render() {
return (
<ReduxProvider store={store}>
<PaperProvider>
<AppNavigator />
</PaperProvider>
</ReduxProvider>
);
}
}
AppNavigator.js
import { createStackNavigator, createAppContainer } from 'react-navigation';
import Home from './../pages/Home';
import InitialDetails from '../pages/LandingPage/initialDetails';
const AppNavigator = createStackNavigator({
Home: {
screen: Home,
navigationOptions: {
header: null,
}
},
InitialDetails: {
screen: InitialDetails,
}
},
{
initialRouteName: 'Home',
});
export default createAppContainer(AppNavigator);
Action
export const USER_INITIAL_INPUT = 'USER_INITIAL_INPUT'
export function updateUserInitialInput (action){
return{
type:USER_INITIAL_INPUT,
action
}
}
Reducer:
import USER_INITIAL_INPUT from './../action/Initial-action'
const initialState = {
userInitalInputFromUser :{
animal : 'tige'
}
}
const InitialReducer = (state = initialState,action) => {
switch(action.type){
case 'USER_INITIAL_INPUT':
return{
...state,
userInitalInputFromUser : action.action
}
default:
return state
}
}
export default InitialReducer
Page where am connecting the Redux.
import React from 'react';
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import {
View,
Text,
ScrollView,
Image,
StatusBar,
StyleSheet,
TouchableOpacity
} from 'react-native';
import {Button } from 'react-native-paper';
// actions
import updateUserInitialInput from './../../action/Initial-action'
import { CommonCSS, initialPageCSS } from '../../Style'
class InitialDetails extends React.Component {
constructor(props) {
super(props)
this.state = {
cookingSkill: 'Beginner',
isVegeterian:false
}
}
static navigationOptions = {
title: "Personalization",
headerStyle: {
backgroundColor: "#fa7776"
},
headerTintColor: "#fff",
headerTitleStyle: {
fontWeight: "bold"
}
};
userInitalInput(whichState,value){
whichState ==='cookingSkill' ?
this.setState({cookingSkill:value}) :
this.setState({isVegeterian:value})
}
render() {
return(
<ScrollView style={CommonCSS.flexContainer}>
<StatusBar backgroundColor="#fa6767" barStyle="light-content" />
{/* Rate your cooking skills */}
<View >
<Text style={initialPageCSS.heading}>Rate your cooking skills!</Text>
</View>
<TouchableOpacity
onPress={this.userInitalInput.bind(this,'cookingSkill','Beginner')}
style={
[initialPageCSS.buttons,
this.state.cookingSkill==='Beginner' ? initialPageCSS.acitveButton : null]
}
activeOpacity={0.5}>
<Image source={require('../../assets/images/avatar.png')} style={initialPageCSS.ImageIconStyle}/>
<Text style={initialPageCSS.TextStyle}> Iam a Beginner </Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this.userInitalInput.bind(this,'cookingSkill','Expert')}
style={
[initialPageCSS.buttons,
this.state.cookingSkill==='Expert' ? initialPageCSS.acitveButton : null]
}
activeOpacity={0.5}>
<Image source={require('../../assets/images/avatar.png')} style={initialPageCSS.ImageIconStyle}/>
<Text style={initialPageCSS.TextStyle}> Iam an Expert </Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this.userInitalInput.bind(this,'cookingSkill','Professional')}
style={
[initialPageCSS.buttons,
this.state.cookingSkill==='Professional' ? initialPageCSS.acitveButton : null]
}
activeOpacity={0.5}>
<Image source={require('../../assets/images/avatar.png')} style={initialPageCSS.ImageIconStyle}/>
<Text style={initialPageCSS.TextStyle}> Iam a Professional </Text>
</TouchableOpacity>
{/* Rate your cooking skills */}
{/* Are you Vegetarian */}
<View>
<Text style={initialPageCSS.heading}>Are you a Vegetarian!</Text>
</View>
<TouchableOpacity
onPress={this.userInitalInput.bind(this,'isVeg',false)}
style={
[initialPageCSS.buttons,
this.state.isVegeterian ? null : initialPageCSS.acitveButton]
}
activeOpacity={0.5}>
<Image source={require('../../assets/images/avatar.png')} style={initialPageCSS.ImageIconStyle}/>
<Text style={initialPageCSS.TextStyle}> Nope, Show me all Recipes </Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this.userInitalInput.bind(this,'isVeg',true)}
style={
[initialPageCSS.buttons,
this.state.isVegeterian ? initialPageCSS.acitveButton : null]
}
activeOpacity={0.5}>
<Image source={require('../../assets/images/avatar.png')} style={initialPageCSS.ImageIconStyle}/>
<Text style={initialPageCSS.TextStyle}> Yes, Hide recipes with meat</Text>
</TouchableOpacity>
<View style = {initialPageCSS.getStartedBtnWrapper}>
<Button
mode="contained"
theme={{
roundness: 5,
width: '90%',
dark: true,
colors: {
primary: '#ec4242',
accent: "#ffffff",
}
}}
contentStyle = {{height:50}}
onPress = {this.props.updateUserInitialInput(this.state)}
>
Get Started
</Button>
</View>
{/* Are you Vegetarian */}
</ScrollView>
);
}
}
InitialDetails.propTypes = {
updateUserInitialInput: PropTypes.func,
userInput : PropTypes.object
}
function mapStateToProps (state) {
alert(JSON.stringify(state))
return{
userInput : state
}
}
// const mapStateToProps = state => ( {
// return{
// userInput : state.userInitalInputFromUser
// }
// } )
const mapDispatchToProps = dispatch => ({
updateUserInitialInput: (userInput) =>
dispatch(updateUserInitialInput(userInput)),
})
export default connect(mapStateToProps, mapDispatchToProps)(InitialDetails)
For now I am not connected with Redux-saga, I am not sure why it throws such an issue in the application. The same approach seems to be working fine in a React application. Can anyone help me fix this issue please?

Error: Cannot read property 'State' of undefined

The error from the debugger and the screen
I created a blog post from local api with the aim of clicking on the "read more" button to navigate to retrieving other remaining items based on the id. However, I made use of navigation but it gave an error of "Cannot read property 'state' of undefined.
import React, {Component} from 'react';
import { StyleSheet, Text, View} from 'react-native';
import Post from './components/Post';
import PostSingle from './components/PostSingle';
import { createStackNavigator, createAppContainer } from 'react-navigation';
const RootStack = createStackNavigator(
{
PostScreen: { screen: Post},
PostSingleScreen:{screen: PostSingle},
}
);
const AppNavigator = createAppContainer(RootStack);
export default class App extends Component {
constructor(props) {
super(props);
};
render() {
return (
<View style={styles.container}>
<AppNavigator/>
</View>
);
}
}
Post.js
The screen loads to POST from which a read more button is pressed to trigger PostSingle
import React, { Component } from 'react';
import {
ScrollView,
StyleSheet,
View,
Text,
InputText,
TouchableOpacity
} from 'react-native';
import axios from 'axios';
export default class Post extends Component{
constructor(props){
super(props);
this.state = {
posts: []
}
}
readMore = (id) => {
this.setState({ id: id})
this.props.navigation.navigate('PostSingleScreen')
}
componentDidMount(){
axios.get(`http://localhost/rest_api_myblog/api/post/read.php`)
//.then(json => console.log(json.data.data[0].id))
.then(json => json.data.data.map(mydata =>(
{
title: mydata.title,
body: mydata.body,
author: mydata.author,
category_name: mydata.category_name,
id: mydata.id
}
)))
//.then(newData => console.log(newData))
.then(newData => this.setState({posts: newData}))
.catch(error => alert(error))
}
render(){
return (
<View>
<ScrollView style={styles.scrollContent}>
<View style={styles.header}>
<Text style={styles.headerText}>Gist Monger</Text>
</View>
{
this.state.posts.map((post, index) =>(
<View key={index} style={styles.container}>
<Text style={styles.display}>
Author: {post.author}
</Text>
<Text style={styles.display}>
Category: {post.category_name}
</Text>
<Text style={styles.display}>
Title: {post.title}
</Text>
<Text style={{overflow:'hidden'}}>
Id: {post.id}
</Text>
<TouchableOpacity style={styles.buttonContainer}
onPress = {() => this.readMore(post.id)}
>
<Text style={styles.buttonText}>
Read More
</Text>
</TouchableOpacity>
</View>
))
}
</ScrollView>
<View style={styles.footer}></View>
</View>
);
}
}
PostSingle.js
The PostSingle is expected to display single post based on the id of the item clicked on the post.
import React, { Component } from 'react';
import {
ScrollView,
StyleSheet,
View,
Text,
TouchableOpacity
} from 'react-native';
import axios from 'axios';
export default class Post extends Component{
constructor(props){
super(props);
this.state = {
posts: []
}
}
componentDidMount(){
axios.get(`http://localhost/rest_api_myblog/api/post/read_single.php?id=${id}`)
.then(json => json.data.data.map(mydata =>(
{
title: mydata.title,
body: mydata.body,
author: mydata.author,
category_name: mydata.category_name,
body: mydata.body
}
)))
.then(newData => this.setState({posts: newData}))
.catch(error => alert(error))
}
render(){
return (
<View>
<ScrollView style={styles.scrollContent}>
<View style={styles.header}>
<Text style={styles.headerText}>Gist Monger</Text>
</View>
{
this.state.posts.map((post, index) =>(
<View key={index} style={styles.container}>
<Text style={styles.display}>
Author: {post.author}
</Text>
<Text style={styles.display}>
Category: {post.category_name}
</Text>
<Text style={styles.display}>
Title: {post.title}
</Text>
<Text style={{overflow:'hidden'}}>
Body: {post.body}
</Text>
</View>
))
}
</ScrollView>
<View style={styles.footer}></View>
</View>
);
}
}
You have to install react-native-gesture-handler along with react-navigation. See this

How to change screen in react native with react-navigation on click of a button?

I have defined all my routes/navigations in my root component (App.js) and am trying to access one of those screens (UserScreen) from a child component(LoginScreen) on click of a button.
Here is my App.js
import React from 'react';
import { StyleSheet, Text, View, TextInput, TouchableHighlight, Button } from 'react-native';
import LoginComponent from './components/LoginComponent';
import { StackNavigator } from 'react-navigation';
class MainWelcome extends React.Component {
render() {
return (
<View>
<Text>Welcome Page</Text>
<Button
title="Login"
onPress={() => this.props.navigation.navigate('Login')}
/>
</View>
);
}
}
class LoginScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<LoginComponent />
</View>
);
}
}
class UserScreen extends React.Component {
render() {
return (
<View>
<Text>Details Screen</Text>
</View>
);
}
}
const RootStack = StackNavigator(
{
Register: {
screen: RegisterScreen,
},
Login: {
screen: LoginScreen,
},
UserPage: {
screen: UserScreen,
},
Welcome: {
screen: MainWelcome,
},
},
{
initialRouteName: 'Welcome',
}
);
export default class App extends React.Component {
render() {
return (
<RootStack />
);
}
}
This is my LoginComponent.js
import React from 'react';
import { StyleSheet, Text, View, TouchableHighlight, TextInput, StackNavigator } from 'react-native';
class LoginComponent extends React.Component {
constructor(){
super();
this.state = {
loginusername: '',
loginpassword: '',
isloggedin: false,
loggedinuser: null,
}
}
render() {
return (
<View>
<Text>Please Log In</Text>
<View>
<TextInput
placeholder="USERNAME"
placeholderTextColor = 'black'
onChangeText={(loginusername) => this.setState({loginusername})}
/>
<TextInput
placeholder="Password"
placeholderTextColor = 'black'
onChangeText={(loginpassword) => this.setState({loginpassword})}
/>
<TouchableHighlight onPress={() => {
{this.props.navigation.navigate('UserPage')}
}
}>
<View>
<Text>Login</Text>
</View>
</TouchableHighlight>
</View>
</View>
);
}
}
export default LoginComponent;
Here in LoginComponent.js, I am doing {this.props.navigation.navigate('UserPage')} to redirect to the userscreen on click of a button but it says TypeError: undefined is not an object (evaluating 'this.props.navigation.navigate'). I am not sure what I am doing wrong and if I should be passing something from the App.js to LoginComponent.js.
If you tried to print your LoginComponent's props you would end up with nothing!,
But what if you pass the navigation as prop to your component like this! :
// App.js
class LoginScreen extends React.Component {
...
<LoginComponent navigation={this.props.navigation}/>
...
}
You will end up with functional navigation prop.
Happy user details navigation :)

react-native Navigator issues

sorry i'm getting this error element type is invalid :expected a string(for built-in components) or a class/function (for composite components)but got:undefined.check the render method of 'Navigator'.
here's the code;
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableHighlight
} from 'react-native';
import ButtonPage from './jara/initialpage';
import NotePage from'./jara/Notescreen';
import HomeScreen from './jara/HomePage';
var NavigationBarRouteMapper = {
LeftButton(route, navigator, index, navState) {
if(index > 0) {
return (
<TouchableHighlight
underlayColor="transparent"
onPress={() => { if (index > 0) { navigator.pop() } }}>
<Text style={ styles.leftNavButtonText }>Back</Text>
</TouchableHighlight>
);
}
else { return null }
},
RightButton(route, navigator, index, navState) {
if (index <= 0) return (
<ButtonPage
onPress ={() => {
navigator.push({
});
}}
customText = 'create Note'
/>
);
},
Title(route, navigator, index, navState) {
return (
<Text style={ styles.title }>Home Page</Text>
);
}
};
class NavProject extends Component{
renderScene(route,navigator){
return(
<route.component navigator = {navigator}/>
);
}
render(){
return(
<View style = {styles.MainContainer}>
<View style = {styles.container}>
<ButtonPage/>
</View>
<Navigator
initialRoute ={{page: 'Home'}}
renderScene ={this.renderScene.bind(this)}
navigationBar ={
<Navigator.NavigationBar
routeMapper = {NavigationBarRouteMapper}
/>
}
configScene ={(route,navigator) =>
Navigator.sceneConfigs.floatFromRight}
/>
</View>
);
}
}
class ReactNote extends Component{
renderScene(route,navigator){
if(index <= 0){
return(
<View style = {styles.container}>
<HomeScreen
onPress={() =>{
navigator.push({});
}}
/>
</View>
);
}
else if(index > 0){
return(
<View styles ={styles.scontainer}>
<NotePage
onPress={() =>{
navigator.pop();
}}
/>
/>
</View>
);
}
}
}
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center',
},
container:{
backgroundColor:'blue',
flex:1,
},
scontainer:{
backgroundColor:'lightblue',
flex:1,
}
});
AppRegistry.registerComponent('NavProject', ()=> NavProject);
I later found out that the renderScene works similarly to the NavigationRouteMapper, where for the individual component pages that were referenced, as shown above.Had to have similar navigation controls.and by that i mean 'navigator.push({});' and 'navigator.pop();' in their respective pages. worked for me.plus i got rid of the renderScene.bind(this) and just wrote the code directly under the renderScene props either, way I think it works.

React-native pushing to other class

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
Image
} from 'react-native';
import First from './First';
export default class Home extends Component{
navSecond(){
this.props.navigator.push({
id: 'First',
title: 'First',
name: 'First',
component: First
})
}
render(){
return(
<View>
<View style={{height:220,backgroundColor:'#DCDCDC'}}>
<Image style={{width:120,height:120,top:50,left:120,backgroundColor:'red'}}
source={require('./download.png')} />
</View>
<View style={{top:30}}>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<TouchableOpacity style= { styles.views} onPress={this.navSecond.bind(this)}>
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> Profile </Text>
</TouchableOpacity>
<TouchableOpacity style= { styles.views1} >
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> Health Tracker </Text>
</TouchableOpacity>
</View>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<TouchableOpacity style= { styles.views2} >
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> Medical Care </Text>
</TouchableOpacity>
<TouchableOpacity style= { styles.views3} >
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> Alerts </Text>
</TouchableOpacity>
</View>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<TouchableOpacity style= { styles.views4} >
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> Health Topics </Text>
</TouchableOpacity>
<TouchableOpacity style= { styles.views5} >
<Text style={{fontSize:20, textAlign:'center',color:'white',top:20}}> My Documents </Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
In this code i need to navigate to First.js using push, but i am not able to do that. By clicking on Profile it should navigate to First.js, here push() is working but that is not navigating to First.js. The above page i set as initial route, then how can i link to all pages?
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity
} from 'react-native';
import Home from './Home';
export default class Prof extends Component{
constructor(){
super()
}
render(){
return (
<Navigator
initialRoute = {{ name: 'Home', title: 'Home' }}
renderScene = { this.renderScene }
navigationBar = {
<Navigator.NavigationBar
style = { styles.navigationBar }
routeMapper = { NavigationBarRouteMapper } />
}
/>
);
}
renderScene(route, navigator) {
if(route.name == 'Home') {
return (
<Home
navigator = {navigator}
{...route.passProps}
/>
)
}
}
}
var NavigationBarRouteMapper = {
LeftButton(route, navigator, index, navState) {
if(index > 0) {
return (
<View>
<TouchableOpacity
onPress = {() => { if (index > 0) { navigator.pop() } }}>
<Text style={ styles.leftButton }>
Back
</Text>
</TouchableOpacity>
</View>
)
}
else { return null }
},
RightButton(route, navigator, index, navState) {
if (route.openMenu) return (
<TouchableOpacity
onPress = { () => route.openMenu() }>
<Text style = { styles.rightButton }>
{ route.rightText || 'Menu' }
</Text>
</TouchableOpacity>
)
},
Title(route, navigator, index, navState) {
return (
<Text style = { styles.title }>
{route.title}
</Text>
)
}
};
As your app grows you'll find out that the Navigator is not enough. So I offer you to use react-native-router-flux. It's works well.
you can simply navigate to any scene and send the data as props.
for example :
import React, { Component } from 'react';
import { ... } from 'react-native';
import Actions from 'react-native-router-flux';
export default class Example extends Component {
componentWillMount() {
}
render() {
return (
<View>
<TouchableOpacity
onPress={()=>{ Actions.media({customData: 'Hello!'}) }}
><Text>Navigate to scene Media</Text></TouchableOpacity>
)
}
}
AppRegistry.registerComponent('Example', () => Example);
Navigating to scene Mediaand passing props named customData with value of 'Hello'