React-native pushing to other class - react-native

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'

Related

How can I keep a check on a radio button in react native?

I'm using a radio button from React Native Paper.
The radio button itself works fine.
But if i move to another page and check the radio button again, the check box cannot be maintained.
How can I keep a check on a radio button?
I am new to React Native.
import React from 'react';
import { StyleSheet, View, TouchableOpacity, Text } from 'react-native';
import { RadioButton } from 'react-native-paper';
import { Actions } from 'react-native-router-flux';
const category = [
{
label: '한식'
},
{
label: '분식'
},
{
label: '카페, 디저트'
}
]
export default class CategoryPage extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
}
}
matchingPage() {
Actions.pop();
}
render() {
return (
<View style={styles.container}>
<View style={{ flex: 9, justifyContent: 'center' }}>
<RadioButton.Group onValueChange={value => this.setState({ value })} value={this.state.value}>
{category.map((data, index) =>
<RadioButton.Item
key={index}
style={styles.radioStyle}
label={data.label}
value={data.label}
color='black' />
)}
</RadioButton.Group>
</View>
<View style={{ flex: 1, alignItems: 'center' }}>
<TouchableOpacity
style={styles.buttonStyle}
onPress={this.matchingPage}>
<Text style={styles.buttonTextStyle}>선택 완료</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
import * as React from 'react';
import { View } from 'react-native';
import { RadioButton } from 'react-native-paper';
const MyComponent = () => {
const [checked, setChecked] = React.useState('first');
return (
<View>
<RadioButton
value="first"
status={ checked === 'first' ? 'checked' : 'unchecked' }
onPress={() => setChecked('first')}
/>
<RadioButton
value="second"
status={ checked === 'second' ? 'checked' : 'unchecked' }
onPress={() => setChecked('second')}
/>
</View>
);
};
export default MyComponent;
You can do something like this
Working Example here
import * as React from 'react';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
import { RadioButton, Text } from 'react-native-paper';
const category = [
{
label: '한식',
},
{
label: '분식',
},
{
label: '카페, 디저트',
},
];
const CategoryPage = () => {
const [value, setValue] = React.useState('first');
return (
<View style={styles.container}>
<View style={{ flex: 9, justifyContent: 'center' }}>
<RadioButton.Group
onValueChange={(value) => setValue(value)}
value={value}>
{category.map((data, index) => (
<RadioButton.Item
key={index}
label={data.label}
value={data.label}
color="black"
/>
))}
</RadioButton.Group>
</View>
<View style={{ flex: 1, alignItems: 'center' }}>
<TouchableOpacity
style={styles.buttonStyle}
onPress={this.matchingPage}>
<Text style={styles.buttonTextStyle}>선택 완료</Text>
</TouchableOpacity>
</View>
</View>
);
};
export default CategoryPage;
const styles = StyleSheet.create({});

Blank Screen with react-native navigation with no error code

Please, look at the debugger and the screen for what could be a problem. However, the code is highly displayed below for your perusal.
More also, I aimed at navigating to another page based on the id of the selected content.
App.js
The App.js is where I defined my stackNavigator
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},
},
{
initialRouteName: "PostScreen"
}
);
const AppNavigator = createAppContainer(RootStack);
export default class App extends Component {
constructor(props) {
super(props);
};
render() {
return (
<View style={styles.container}>
<AppNavigator/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#F3F3F3',
}
});
Post.js
I have tried to delete alignItem = center. In fact I deleted my style to see if there is any blocking the screen from coming up.
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 = () => {
()=> this.props.navigation.navigate('PostSingleScreen');
debugger;
}
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()}
>
<Text style={styles.buttonText}>
Read More
</Text>
</TouchableOpacity>
</View>
))
}
</ScrollView>
<View style={styles.footer}></View>
</View>
);
}
}
const styles = StyleSheet.create({
header: {
flex: 1,
height:40,
marginTop:50,
marginBottom:10,
flexDirection: 'row',
justifyContent:'center',
},
display: {
margin: 3,
fontSize: 16
},
headerText: {
fontWeight: 'bold',
fontSize: 40,
color: '#6200EE'
},
container: {
backgroundColor:'#efefef',
padding: 20,
margin: 5,
borderRadius:20,
justifyContent: 'center',
alignItems: 'center'
},
footer: {
flex: 1,
backgroundColor:'#000',
marginBottom:50
},
buttonContainer:{
height: 30,
width: 200,
marginTop: 15,
justifyContent: 'center',
alignItems: 'center',
borderRadius: 15,
backgroundColor:'#6200EE'
},
buttonText: {
alignContent: 'center',
color: 'white'
}
});
PostSingle.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text
} from 'react-native';
import axios from 'axios';
export default class Post extends Component{
constructor(props){
super(props);
}
render(){
return (
<View>
<Text>My text</Text>
</View>
);
}
}
const styles = StyleSheet.create({
});
I did not test this code, but try to add flex: 1 to your container style. the main containers/components don't stretch if you don't tell them to
const styles = StyleSheet.create({
container: {
backgroundColor: '#F3F3F3',
flex: 1,
}
});
also, to check if the components render (helps debugging where the problem is), write a console log in every component's componentDidMount. if they mount, but nothing is visible, it's most likely a CSS issue. If it wasn't, it would throw errors instead of blank screen
second issue is, when you navigate you need to have params with react-navigation. the syntax for it is like this:
this.props.navigation.navigate('PostSingleScreen', { params })
so, if you have { id: someId } in your params, in the component you navigated to you will have {this.props.navigation.state.params.id}. so basically those params are inside navigation.state.params where you navigate
Let me help you with your second question. First, it is easier as said by just specifying params in your navigation.
For instance,
readMore = (id) => {
this.props.navigation.navigate('PostSingleScreen', {id:id})
}
However, in your TouchableOpacity, onPress method i.e. onPress = {() => this.readMore(post.id)}
In your PostSingle.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
Button
} from 'react-native';
import axios from 'axios';
class PostSingle extends Component{
constructor(props){
super(props);
this.state = {
posts: []
}
}
componentDidMount() {
const id = this.props.navigation.state.params.id;
axios.get(`http://localhost/rest_api_myblog/api/post/read_single.php?id=${id}`)
.then(json => json.data)
.then(newData => this.setState({posts: newData}))
.catch(error => alert(error))
}
render(){
return (
<View style={styles.container}>
<Text style={styles.display}>
{this.state.posts.title}
</Text>
<Text style={styles.display}>
{this.state.posts.author}
</Text>
<Text style={styles.display}>
{this.state.posts.category_name}
</Text>
<Text style={styles.display}>
{this.state.posts.body}
</Text>
</View>
);
}
}
I hope it helps
i would suggest using flaltist for this, and not this.state.map. this should give you the same outcome
readMore(id){
//do whatever you want with the id
this.props.navigation.navigate('PostSingleScreen',{id:id}); //or pass it as a prop
debugger;
}
renderItem = ({ item, index }) => {
return (
<View key={index} style={styles.container}>
<Text style={styles.display}>
Author: {item.author}
</Text>
<Text style={styles.display}>
Category: {item.category_name}
</Text>
<Text style={styles.display}>
Title: {item.title}
</Text>
<Text style={{overflow:'hidden'}}>
Id: {item.id}
</Text>
<TouchableOpacity style={styles.buttonContainer}
onPress = {() => this.readMore(item.id)}
>
<Text style={styles.buttonText}>
Read More
</Text>
</TouchableOpacity>
</View>
);
};
render(){
return (
<View style={{flex:1}}>
<FlatList
style={{flex:1}}
data={this.state.posts}
renderItem={this.renderItem}
numColumns={1}
keyExtractor={(item, index) => item.id} //this needs to be a unique id
ListHeaderComponent = {
<View style={styles.header}>
<Text style={styles.headerText}>Gist Monger</Text>
</View>}
/>
<View style={styles.footer}/>
</View>
);
}
If you are using react-navigation 5.x then it might be possible that you are adding CSS
alignItems: "center"
to your root file i.e. App.js or index.js I just removed it and it starts working for me.

undefined is not an object (evaluating'_this2.props.navigation.navigate') - React Native

I am having trouble navigating through screens with a simple button.
This is my App.js
export default class App extends Component<Props> {
render() {
return (
<AppStackNavigator/>
);
}
}
const AppStackNavigator = StackNavigator({
Login: { screen: LoginScreen },
Home: { screen: HomeScreen },
},{
navigationOptions: {
gesturesEnabled:false
}
})
Login.js
export default class Login extends Component {
render() {
return(
<SafeAreaView style={styles.container}>
<StatusBar barStyle='light-content'/>
<KeyboardAvoidingView behavior='padding' style={styles.container}>
<TouchableWithoutFeedback style={styles.container} onPress={Keyboard.dismiss}>
<View style={styles.logoContainer}>
<View style={styles.logoContainer}>
<Image style={styles.logo}
source={require('../images/logo/logo.png')}>
</Image>
<Text style={styles.title}>
Sports Chat App
</Text>
</View>
<View style={styles.infoContainer}>
<TextInput style={styles.input}
placeholder="Enter name"
placeholderTextColor='#ffffff'
keyboardType='default'
returnKeyType='next'
autoCorrect={false}
onSubmitEditing={()=> this.refs.phoneNumber.focus()}
/>
<TextInput style={styles.input}
placeholder="Enter phone number"
placeholderTextColor='#ffffff'
keyboardType='phone-pad'
ref={'phoneNumber'}
/>
<TouchableOpacity style={styles.buttonContainer}>
<Button title='LogIn' onPress={()=>this.props.navigation.navigate('Home')}/>
</TouchableOpacity>
</View>
</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
};
LoginScreen.js
class LoginScreen extends Component {
render(){
return (
<View>
<Login>
</Login>
</View>
);
}
}
I keep getting the error undefined is not an object (evaluating'_this2.props.navigation.navigate') whenever i try use the Login button in Login.js,
I want this to navigate to the home screen but cant figure out why this keeps happening.
If i try do it without the components it works fine.
Click to View error message
Add a navigation props to Login in LoginScreen.js, Because LoginScreen has props navigation but Login don't.
render(){
return (
<View>
<Login navigation ={this.props.navigation}>
</Login>
</View>
);
}
App.js
import React, { Component } from "react";
import { Text, View } from "react-native";
import AppStackNavigator from "./AppStackNavigator";
export default class App extends Component<Props> {
render() {
return <AppStackNavigator />;
}
}
AppStackNavigator
import React, { Component } from "react";
import { StackNavigator } from "react-navigation";
import { View, Text, TouchableOpacity } from "react-native";
const LoginScreen = props => (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Login navigation={props.navigation} />
</View>
);
const HomeScreen = () => (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Home</Text>
</View>
);
const Login = props => (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<TouchableOpacity
onPress={() => {
props.navigation.navigate("Home");
}}
>
<Text>GO to home from login</Text>
</TouchableOpacity>
</View>
);
export default (AppStackNavigator = StackNavigator(
{
Login: { screen: LoginScreen },
Home: { screen: HomeScreen }
},
{
headerMode: "none",
navigationOptions: {
gesturesEnabled: false
}
}
));
You need to access the navigation prop in the component. Check the official guide.
reactnavigation Official guide
import React from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';
class MyBackButton extends React.Component {
render() {
return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />;
}
}
// withNavigation returns a component that wraps MyBackButton and passes in the
// navigation prop
export default withNavigation(MyBackButton);

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

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

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.