How to change components states from another component? - javascript

I have an ApplicationHeader component in my applicationn that is called in App.js
ApplicationHeader.js
export default class ApplicationHeader extends Component {
constructor(props){
super(props)
this.state = {
loggedUser: null,
}
}
render() {
return(
<View style={AppStyle.header}>
<View style={{flex:1}}>
<Image source={require('../assets/images/logo.png')} style = { AppStyle.headerLogo}/>
</View>
<View style={{flex:0.1}}>
<Image source={require('../assets/images/bag-topbar.png')} style = { AppStyle.headerBag}/>
</View>
<View style={{flex:0.15}}>
<Image source={this.state.loggedUser !== null ? imgWishListLogged : imgWishList} style = { AppStyle.headerWishlist}/>
</View>
</View>
);
}
}
My App.js renders ApplicationHeader
render() {
return (
<SafeAreaView forceInset={{ bottom: 'never'}} style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<ApplicationHeader />
<AppNavigator />
</SafeAreaView>
);
}
Now, In my Homepage.js I would like to send userLogged state or prop to ApplicationHeader to change the icon when user is logged.
class Homepage extends Component {
render() {.....

Change state to props (or pass the props to the state in your constructor)
<Image source={this.props.loggedUser !== null ? imgWishListLogged : imgWishList} style = { AppStyle.headerWishlist}/>
and then pass the variable in the props of the ApplicationHeader
<ApplicationHeader loggedUser={myVar} />
More info on props here

generally the answer is that you "pass the data higher up" so you don't think about it as "sending from one component to another," you let one component work up the state tree to pass the authentication status higher up in the component tree.
in your example you would not store the state in the lower-level objects, just pass them from the higher components as props.

After some attempts, the best way I found was to implement Redux.
Then, with Redux I just used isLoggedUser prop like follow:
{!isLogged && ( <Image source={imgWishList} style = { AppStyle.headerWishlist}/>)}
{isLogged && ( <Image source={imgWishListLogged} style = { AppStyle.headerWishlist}/>)}

Related

Cannot set property '0' of null in React Native ref

I am trying to set up a React Native ref like here, only in a class component:
https://snack.expo.io/PrrDmZ4pk
Here's my code:
class DetailBody extends Component {
constructor() {
super();
this.myRefs = React.createRef([]);
}
clickText(index) {
this.myRefs.current[index].setNativeProps({ style: { backgroundColor: '#FF0000' } });
}
render() {
if (this.props.article.json.results.length === 0) {
return <Loading />;
}
return (
<View >
<View>
<View ref={this.props.highlight} nativeID="some-id" >
{this.props.article.json.results.map((content, index) => (
<TouchableOpacity onPress={() => this.clickText(index)}>
<View key={index} ref={el => this.myRefs.current[index] = el}>{content}</View>
</TouchableOpacity>
</View>
</View>
</View>
This should theoretically let me add a background colors when my ref is clicked, much like the snack I linked to above.
However what I actually see is this:
This seems to be related to .current inside my ref being null, despite passing a default value.
How do I fix this error?
If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element.
Haven't really used it this way but I think you might just need to do this in the constructor:
this.myRefs = React.createRef();
this.myRefs.current = [];

Can we use this.props.map as well as this.props.navigation in single class to navigate to another screen

I have used this.props.maps as well as this.props.navigation which is showing an error:
this.props.navigation.navigate is undefined object
Trying to navigate to another page by rendering the firebase database but getting error but the same code i tried by simple creating a view and navigating to another page then it is working
export default class ItemComponent extends Component {
constructor(props) {
super(props);
// need to bind `this` to access props in handler
this._onEditLibrary = this._onEditLibrary.bind(this);
}
static propTypes = {
items: PropTypes.array.isRequired
};
_onEditLibrary=()=> {
this.props.navigation.navigate('EditLibrary');
};
render() {
return (
<View style={styles.itemsList}>
<TouchableOpacity onPress={this._onEditLibrary}>
{this.props.items.map((item, index) => {
return (
<View key={index}>
<ImageBackground source={item.Image} style={ { height:150, width:150}}>
<Text style={styles.itemtext}>{item.Name}</Text>
</ImageBackground>
</View>
)
})
}
</TouchableOpacity>
</View>
);
}
}
Need to navigate to another page
Try this out
export default class ItemComponent extends Component {
constructor(props) {
super(props);
// need to bind `this` to access props in handler
this._onEditLibrary = this._onEditLibrary.bind(this);
}
static propTypes = {
items: PropTypes.array.isRequired
};
_onEditLibrary=()=> {
this.props.navigation.navigate('EditLibrary');
};
render() {
return (
<View style={styles.itemsList}>
{this.props.items.map((item, index) => {
return (
<TouchableOpacity key={index} onPress={this._onEditLibrary}>
<ImageBackground source={item.Image} style={ { height:150, width:150}}>
<Text style={styles.itemtext}>{item.Name}</Text>
</ImageBackground>
</TouchableOpacity>
)
})
}
</View>
);
}
}

How to call a function in a React Native class from a different module

In my app, I have defined a default class A in module xyz.js that renders a page on my navigation stack. Depending on one of class A's state variables, the views that are rendered differ. For example, if the app is placed in an "edit mode", then an editing view is rendered in addition to the other standard views rendered when the app is not in the "edit mode". I can't figure out how to change that state variable from a different module abc.js and cause the views associated with the instantiated class A to re-render. In my module abc.js, I create the navigation stack and I have an onPress handler for a touchableHighlight button to place the app in "edit mode". In that handler, I attempt to call a function "Edit()" in class A. But the function does not seem to get invoked. It may have something to do with binding, but that concept is not something I fully understand.
Here is what I have:
Module abc.js:
import XYZ from './xyz';
import {Edit} from './xyz';
import { pencilEditButton } from './Images';
const App = createStackNavigator(
{
Home: {
screen: My App,
navigationOptions: ({ navigation }) => ({
title: 'myApp',
headerRight: (
<View>
<TouchableHighlight
onPress={() => Edit()}
underlayColor="gray">
<View>
<Image source={pencilEditButton} style={styles.navigationButtonImage} />
</View>
</TouchableHighlight>
</View>
),
}),
},
}
);
export default createAppContainer(App);
Module xyz.js:
export default class XYZ extends React.Component {
constructor(props) {
super(props);
this.state = {
editMode: false,
};
};
// Create a method to handle the press of the edit button on the navigation bar
Edit() {
console.log("editMode: ", editMode);
this.setstate({ editMode: true });
console.log("editMode: ", editMode);
alert('User wants to edit a mix!');
};
render() {
return (
<View style={styles.container}>
{ this.state.editMode === true ?
<TouchableHighlight
onPress={this._onXPressed}
underlayColor="white">
<View style={[styles.flowRight, styles.controlButton]}>
<Text style={styles.buttonText}>{'Edit Mode'}</Text>
</View>
</TouchableHighlight>
:
<TouchableHighlight
onPress={this._onYPressed}
underlayColor="white">
<View style={[styles.flowRight, styles.controlButton]}>
<Text style={styles.buttonText}>{'Non Edit Mode'}</Text>
</View>
</TouchableHighlight>
}
</View>
);
}
}
So as you can see, there is a function called "Edit()" after the constructor in class XYZ of module xyz.js. This function is called from module abc.js when the edit button is pressed. But when the edit button is pressed, the state is not updated, the alert view is not displayed, and the views are not re-rendered. How do I correctly call Edit() so that the state variable "editMode" is updated and the views are re-rendered?
If you want to follow the pattern you are using, it needs to be handles inside your 'My App' component which gets render in stack navigator. You have to use refs
Go through the following code example to find out how to call Edit function.
import XYZ from './xyz';
export default class MyApp extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: 'myApp',
headerRight: navigation.state.params && navigation.state.params.edit ? (
<View>
<TouchableHighlight
onPress={() => navigation.state.params.edit()}
underlayColor="gray"
>
<View>
<Image source={pencilEditButton} style={styles.navigationButtonImage} />
</View>
</TouchableHighlight>
</View>
) : null,
})
constructor(props) {
super(props);
this.onEdit = this.onEdit.bind(this);
}
componentDidMount() {
this.props.navigation.setParams({ edit: this.onEdit });
}
onEdit() {
if (this.xyz_Ref) {
this.xyz_Ref.Edit();
}
}
render() {
return (
<View>
<XYZ ref={ref => this.xyz_Ref = ref} />
</View>
);
}
}

React native: rendering conditional component based on state value change in Modal

I have a requirement of showing a tab like behavior inside a react native Modal
I have started by creating a state variable selectedSub which is initialized with value 'from'
Now my modal has 2 TouchableHighlight as below
_availabiltyModal() {
return (
<TouchableHighlight
onPress={() => { this.setState({ selectedSub: 'from' }) }}
activeOpacity={0.9}
style={[styles.tab, this.state.selectedSub == 'from' && styles.active]}>
<RkText rkType="header" style={this.state.selectedSub == 'from' && styles.activeText}>From</RkText>
</TouchableHighlight>
<TouchableHighlight
onPress={() => { this.setState({ selectedSub: 'to' }) }}
activeOpacity={0.9}
style={[styles.tab, this.state.selectedSub == 'to' && styles.active]}>
<RkText rkType="header" style={this.state.selectedSub == 'to' && styles.activeText}>To</RkText>
</TouchableHighlight>
{this._renderPicker()}
)}
These two are responsible to change the state param selectedSub as required.
Based on this state param i am conditionally showing another component i made and imported as below
_renderPicker() {
if (this.state.selectedSub == 'from') {
return <TimePicker screenProps={{ time: this.state.selectedAvailabilty.from }} />
} else {
return <TimePicker screenProps={{ time: this.state.selectedAvailabilty.to }} />
}
}
I have called this function in the Modal below the TouchableHighlight's
Now as per the RN docs when ever the state variable is updated with this.setState() method the component should re-render. Everything else is working fine (TouchableHighlight styles changing) and also the updates to the state are reflecting in the console. But the _renderPicker function does not return the changed view and is always stuck on the view which was set when the parent was initialized as pointed earlier.
Could somebody help me point the problem here which i might have been overlooking. Also on the side note all this calls are actually directly made outside the main render() method. Could that be a possible issue
------update------
here is the complete reference
render() {
return({this._availabiltyModal()}
<View style={appStyles.tagsWrapper}>
{this.state.week.map((day, i) => {
return (
<TouchableHighlight
key={i}
activeOpacity={0.9}
style={[appStyle.mr10, appStyle.mb10]}
onPress={() => {
this.setModalVisible(true, day);
}}>
<Text style={appStyle.tag}>{day}</Text>
</TouchableHighlight>
)
})}
</View>
)
}
Move the _renderPicker method inside the render() method like...
render() {
...
{this._renderPicker()}
...
}
Looking at the code of the MODAL component from react-native
render(): React.Node {
....
const innerChildren = __DEV__ ? (
<AppContainer rootTag={this.context.rootTag}>
{this.props.children}
</AppContainer>
) : (
this.props.children
);
return (
<RCTModalHostView
....>
<View style={[styles.container, containerStyles]}>
{innerChildren}
</View>
</RCTModalHostView>
);
}
The state you are changing are of the component that use the modal component thats render its children through the upper function.. when the state update it only re render the component whose state is updated.. so somewhere down rendering child inside component it does not get re render until force re render is applied.
Here is an helpful article to further explain how exactly this functions, forcefully re-rendering the child component

Is there any chance to use a component as a global ActivityIndicator on React-Native

Is there any chance to use a component as a global ActivityIndicator which has transparent color and had been created by me on React-Native?
Details:
I use a redux store to update the UI. So I intend to show an ActivityIndicator by updating the store.
I've created an ActivityIndicator component with name ActIndicator.
I have a main App component that contains the app.
I have a Root component that wraps the ActIndicator and App components.
The ultimate code of render method of Root component looks like the following:
render() {
if (this.state.showActivityIndicator) {
return(
<ActIndicator>
<App />
</ActIndicator>
)
}
return (</App>)
}
I've tried several methods but I can not be successful.
I guess my brain is stopped.
I also guess there may be a logic mistake.
const withLoadingOverlay = (Component) => class withLoadingOverlayView extends React.Component { props: withLoadingOverlayProps
// Indicator view styles loadingOverlay = (style) => (
<View style={[style, styles.someDefaultStyles]}>
<ActivityIndicator color={someColor} size="large" />
</View> )
render() {
const { pending, ...passProps } = this.props;
const { width, height } = Dimensions.get('window');
return (
<View style={{ flex: 1 }}>
<Component {...passProps} />
{pending && this.loadingOverlay({ width, height })}
</View>
); } };
I used to wrap whole container with HOC and with redux action to set on start pending prop true and on success or fail to set on false so this prop will be consumed by HOC and indicator will be displayed only when pending is set on true.
In container you have to wrap component in connect
export default connect(
(state) => ({
pending: state.reducer.pending, // pending prop should be here
}),
(dispatch) => ({ dispatching redux actions })
)(withLoadingOverlay(WrappedComponent));
I don't think you're supposed to pass App as a child, the way I use it is more like this:
render() {
if (this.state.showActivityIndicator) {
return(
<View>
<ActivityIndicator />
<App />
</View>
)
}
return (<App />)
}
but it would probably be better to set it up like this:
render() {
return (
<View>
<ActivityIndicator animating={this.state.showActivityIndicator} />
<App />
</View>
)
}

Categories

Resources