Reputation: 55
hello guys I have the script App.js that is running in the entire application and has my page to react navigation (drawer) that is Screen3.js
I want to call my state speed. from App.js to Screen3. my speed are changing every 10 seconds.
App.js
import Screen1 from './pages/Screen1';
import Screen2 from './pages/Screen2';
import Screen3 from './pages/Screen3';
import CustomSidebarMenu from './CustomSidebarMenu';
global.currentScreenIndex = 0;
class NavigationDrawerStructure extends Component {
toggleDrawer = () => {
//Props to open/close the drawer
this.props.navigationProps.toggleDrawer();
};
constructor(props) {
super(props)
this.state = {
speed: ''
}
and rest script
Screen3.js
import React, { Component } from 'react';
import { SectionList, FlatList, View, Text, TextInput, Button, StyleSheet, Image, PermissionsAndroid, ActivityIndicator, Platform, TouchableOpacity, List, Drawer, Container, Header, Content } from 'react-native';
import Geolocation from '@react-native-community/geolocation';
import { App } from '../App'
export default class Screen3 extends Component {
render() {
return (
<View style={styles.MainContainer}>
<Text style={{ fontSize: 23 }}> My Screen {global.currentScreenIndex + 1} </Text>
<Text style={{ justifyContent: 'center', alignItems: 'center', marginTop: 16 }}>
myspeed: {App.this.props.speed} //< --- MY PROBLEM HERE <---!!
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
paddingTop: 20,
alignItems: 'center',
marginTop: 50,
justifyContent: 'center',
},
});
```
Upvotes: 0
Views: 635
Reputation: 35569
There are plenty of options available if you wanted to maintain some global values.
Redux
Store that parameter in redux store and connect your component wherever you need it.
Event Listener
You can use NativeEventEmitter
and pass value along with that call. Now add that event listener to the component where you need updated value and that's it.
Global state
Store value in App level state and pass it along with all the child, but I will not prefer this option as this parameter will be passed to other components also where it is not actually required.
Upvotes: 3
Reputation: 9769
Pass state like this from App.js component
<App speed={this.state.speed}/>
and access like this in your Screen3 component
<Text style={{ justifyContent: 'center', alignItems: 'center', marginTop: 16 }}>
myspeed: {this.props.speed}
</Text>
Note- As you are accessing that isn't the way to access state from parent to child component.
If you don't want to pass state(speed) like this then use context Api for that so that you could access where ever you want.
Upvotes: 0