passing array state to another class react native - react-native

I am new to React Native. I am making a lunch picker app for practice, and I wonder how to pass array of state to another class.
What I want to do is: show all data of array in child screen, so users can check the data by clicking on a button.
However, it seems like my code returns null array instead of getting original array. All codes are in one file, App.js
Home screen
class HomeScreen extends React.Component {
//initial
constructor(props) {
super(props);
this.state = {
isReady: false,
myMenu: '????',
menutext: '',
randomArray: ['a', 'b', 'c'],
};
}
render() {
return (
<View style={[styles.mainContainer]}>
<DetailsScreen menuListAA={this.state.randomArray} />
<Button
label="Show all menu"
onPress={() => {
/* 1. Navigate to the menu page route with params */
this.props.navigation.navigate('Details', {
itemId: 0,
otherParam: 'Show all menu',
});
}}
/>
</View>
Details screen
class DetailsScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
static navigationOptions = {
title: 'All menu',
};
loadMenuList() {
const allMenuList = this.props.menuListAA;
return allMenuList.map((item, index) => <Text key={index}>{item}</Text>);
}
render() {
return (
<ScrollView>
<View style={styles.row}>{this.props.menuListAA}</View>
<Button
label="Go back"
onPress={() => this.props.navigation.goBack()}
/>
</ScrollView>
);
}
}
const RootStack = createStackNavigator(
{
Home: HomeScreen,
Details: DetailsScreen,
},
{
initialRouteName: 'Home',
}
);
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
Let me know if you need more information.

Please replace your code with one below :
Home screen
class HomeScreen extends React.Component {
//initial
constructor(props) {
super(props);
this.state = {
isReady: false,
myMenu: '????',
menutext: '',
randomArray: ['a', 'b', 'c'],
};
}
render() {
return (
<View style={[styles.mainContainer]}>
<DetailsScreen menuListAA={this.state.randomArray} />
<Button
label="Show all menu"
onPress={() => {
/* 1. Navigate to the menu page route with params */
this.props.navigation.navigate('Details', {
itemId: 0,
otherParam: 'Show all menu',
});
}}
/>
</View>
Doubts Detail : replace View with Text component
class DetailsScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
static navigationOptions = {
title: 'All menu',
};
loadMenuList() {
const allMenuList = this.props.menuListAA;
return allMenuList.map((item, index) => <Text key={index}>{item}</Text>);
}
render() {
return (
<ScrollView>
//change View with Text as view cannot render characters and error says the same
<Text style={styles.row}>{this.props.menuListAA}</Text>
<Button
label="Go back"
onPress={() => this.props.navigation.goBack()}
/>
</ScrollView>
);
}
}
const RootStack = createStackNavigator(
{
Home: HomeScreen,
Details: DetailsScreen,
},
{
initialRouteName: 'Home',
}
);
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}

you can pass data from parent to child by set props for child component like this: <Child data={this.state.yourData} /> //the props name is data,
then in child component in componentWillMount() you can access it:
ComponentWillMount(){
this.setState({childData: this.props.data}) // childData is an state of child component,rename it to your own`
}
in some case data maybe changed so we must to check this in componentDidUpdate() :
componentDidUpdate(){
if(this.props.data != this.state.childData){ //it is necessary because this function called many time's
this.setState({childData: this.props.data})
}
if you was in parent & want to give any data from child you must pass a function that returned data as like below:
<Child getData={(value)=> console.log(value)} />
then in your child you can do this:
this.props.getData(anyDataYouWantGetInParent)
hope this answer will be helpful,let me know any question
good luck.

Related

How to pass a function as a prop in React-Native

I'm currently working on an app in React-Native and it includes DrawerNavigation, SwitchNavigation and AppContainer. There is a method at header.js that i need to use in order to make the drawer functionable (toggleDrawer())
I've tried passing the function at the DrawerNavigator but it didnt work.
export default class Header extends React.Component {
render() {
return (
<View style={styles.container}>
<TouchableOpacity
onPress={() => {
this.props.navigation.toggleDrawer();
}}
>
<Image
source={require("/Users/Rron/AnketaApp/assets/hamburger-
icon.jpg")}
style={styles.imageStyle}
/>
</TouchableOpacity>
</View>
);
}
}
});
export default class HomeScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
let drawerLabel = "Home";
return { drawerLabel };
};
render() {
return (
<View style={styles.container}>
<Header {...this.props}/>
<ScrollView>
<Content />
</ScrollView>
</View>
);
}
}
export default class DrawerNavigator extends React.Component {
render() {
return <AppContainer />;
}
}
const AppDrawerNavigator = createDrawerNavigator(
{
Home: {
screen: HomeScreen
},
Anketa: {
screen: AnketaScreen
}
}
);
const AppContainer = createAppContainer(
createSwitchNavigator({
Introduction: {
screen: IntroductionScreen
},
Drawer: {
screen: AppDrawerNavigator``
}
})
);
The error says
this.props.navigation.toggleDrawer is not a function and its not
defined.
What you can do is import { DrawerActions } from 'react-navigation-drawer' and use it as it says in the docs.
this.props.navigation.dispatch(DrawerActions.toggleDrawer());
Also make sure that you components are inside the navigation.

How to set timer in react-navigation?

I tried navigate react-native-navigation with timer. So if the value of the timer is '5', navigation to 'Home' is called.
I used ternary operation to call navigation.
import React from 'react';
import {
View,
Text,
Button
} from 'react-native';
import {styles} from './AppStyle'
import {createStackNavigator, createAppContainer} from 'react-navigation'
import HomeScreen from './Pages/Home'
class Timer extends React.Component{
constructor(props){
super(props)
this.state = {
time : props.count
}
}
componentDidMount(){
this.addInterval = setInterval( () => this.increase(), 1000)
}
componentWillUnmount(){
clearInterval(this.addInterval)
}
increase(){
this.setState((_state, _props) => ({
time: parseInt(this.state.time) + 1
}))
}
render(){
return(
<Text> {this.state.time} </Text>
);
}
}
class StartScreen extends React.Component {
render(){
return (
<View style={styles.container}>
<View style={styles.navbar}>
<Timer count='0'/>
{this.props.count == '5' ? ()=>this.props.navigation.navigate('Home') : ''}
</View>
</View>
);
};
}
const HomeNavigator = createStackNavigator(
{
Home: {
screen: HomeScreen
}
}
)
const StartNavigator = createStackNavigator(
{
Start: {
screen: StartScreen
},
Main: {
screen: HomeNavigator
}
},
{
mode: 'modal',
headerMode: 'none'
},
{
initialRouteName: 'Start'
}
)
const AppContainer = createAppContainer(StartNavigator);
export default class App extends React.Component {
render() {
return <AppContainer/>
}
}
I expect when count is '5' screen will navigate to 'Home', but i got this issue "Invariant Violation: Invariant Violation: Text Strings must be rendered within a component"
Create an onIncrease prop for your Timer component, rather than directly making the function call within render.
class Timer extends React.Component {
/* component functions */
increase = () => {
const { time } = this.state
const { onIncrease } = this.props
const newTime = time + 1
onIncrease(newTime)
this.setState({ time: newTime })
}
/* render function */
}
class StartScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<View style={styles.navbar}>
<Timer
count={0}
onIncrease={count => {
if (count === 5) {
this.props.navigation.navigate('Home')
}
}}
/>
</View>
</View>
)
}
}
You can also use setTimeout, instead of doing:
{this.props.count == '5' ? ()=>this.props.navigation.navigate('Home') : ''}
you can do
{ setTimeout(()=>{ this.props.navigation.navigate("Home") }, 3000);}

Update value in StackNavigation custom header

I defined a custom view as a component for headerRight property in navigationOptions as bellow:
static navigationOptions = ({ navigation }) => {
return {
headerRight: navigation.getParam('headerRight', null),
};
};
and then in componentDidMount:
this.props.navigation.setParams({
headerRight: (<MessageDetailsHeader {...this.props}
title = {this.state.headerTitle}
subTitle = {this.state.headerSubTitle}
online = {this.state.online}
/>)
})
also i defined some state for updating values:
constructor(props) {
super(props);
this.state = {
headerTitle: null,
headerSubTitle: null,
headerOnline: false
};
}
Custom header view component defined as bellow:
export default class MessageDetailsHeader extends React.Component {
constructor(props) {
super(props);
this.state = {
title: this.props.title,
subTitle: this.props.subTitle,
online: this.props.online
};
}
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps.title,
subTitle: nextProps.subTitle,
online: nextProps.online,
})
}
render() {
return (
<View style={styles.headerContainer}>
<View style={styles.headerDetailsContainer}>
<Text style={styles.headerTitle}>{this.state.title}</Text>
<Text style={styles.headerSubTitle}>{this.state.subTitle}</Text>
</View>
<Avatar small rounded source={require('../images/no-profile.png')} activeOpacity={0.7} avatarStyle={this.state.online? styles.avatarOnline: styles.avatarOffline}/>
</View>
);
}
}
I need to call setState in screen and then update Custom View in navigation header, is this a right way?
Thanks in advance
Solved!
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
headerRight: <MessageDetailsHeader
title={params.headerTitle}
subTitle={params.headerSubTitle}
online={params.headerOnline}
/>
};
};
and then called bellow code to set new value, easily!
this.props.navigation.setParams({
headerSubTitle: 'online',
});

instance member is not accessible

How can I access class functions from inside stack navigator header? Is this possible?
What I'm trying to achieve is to call a function when I press the stack navigator header title.
class Dashboard extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerTitle: (
<View style={header.addressView}>
<Text
style={header.titleAddress}
onPress={() => {
this._show().bind(this);
}}>
/>
</View>
),
};
};
_show(){
this.setState({ visibleModal: 1 })
}
constructor(props) {
super(props);
this.state = {
visibleModal: null,
};
}
render() {
...........
}
}
export default Dashboard;
class Dashboard extends React.Component {
static navigationOptions = ({ navigation }) => {
const showParams = navigation.getParam("show",()=>{});
//Access the params like this.
return {
headerTitle: (
<View style={header.addressView}>
<Text
style={header.titleAddress}
onPress={showParams}>
/>
</View>
),
};
};
_show(){
this.setState({ visibleModal: 1 })
}
//Too add this.
componentDidMount(){
this.props.navigation.setParams({show:()=>this._show()});
}
constructor(props) {
super(props);
this.state = {
visibleModal: null,
};
}
render() {
...........
}
}
export default Dashboard;
This is how you access the variables or states inside a class and make it available for the static navigationOptions function.
Reference

How to dynamically change the header title text in a react native app?

I have been struggling with something that sounds simple. I have been trying to get button when onpressed is called. Have tried several combinators but nothing works. Any ideas?
export default class JobScreen extends React.Component {
constructor(props) {
super(props);
}
static navigationOptions = ({navigation}) => ({
title: "Chat with"
});
onPressLearnMore(nav) {
// how do I update the title header
console.log("On Pressed" + nav)
}
render() {
const {navigate} = this.props.navigation;
return (
<View style={styles.container}>
<Button
onPress={() => {this.onPressLearnMore(navigate)}}
title="Learn More"
color="#841584"
/>
</View>
);
}
}
Since the navigationOptions has access to the navigation object, you can set some param on the current screen with this.props.navigation.setParam({ title: ‘some title’ }) and then access it in navigationOptions like this
static navigationOptions = ({ navigation }) => {
const { state: { params = {} } } = navigation;
return {
title: params.title || ‘default title’,
};
}