React Native setState not re-rendering - reactjs

Expected behaviour of this component is like this: I press it, selectedOpacity() function is called, state is updated so it now renders with opacity=1.
But for some reason, after calling this.setState, it is not being re-rendered. I have to click this component again to make it re-render and apply changes of opacity from state.
export default class Category extends Component {
state = {
opacity: 0.5
}
selectedOpacity() {
// some stuff
this.setState({opacity: 1})
}
render() {
return(
<TouchableOpacity style={[styles.container, {opacity: this.state.opacity}]} onPress={() => {
this.selectedOpacity();
}}>
</TouchableOpacity>
)
}

I think what you are missing is binding of selectedOpacity(), else this would be undefined in it AFAIK.
Also better move the assignment of state to a constructor().
constructor(props) {
super(props);
this.state = {};
this.selectedOpacity = this.selectedOpacity.bind(this);
}
Also change to the following because creating an arrow function inside render affects performance.
onPress={this.selectedOpacity}

Change selectedOpacity to arrow function:
selectedOpacity = () => {
this.setState({opacity: 1})
}
Then:
onPress={this.selectedOpacity}
Edit: The react documentation says its experimental and the syntax is called public class field syntax.

Try change onpress to
onPress={() => this.selectedOpacity()}

Related

React does not rerender when a prop changes

I'm trying to develop an edit mode for a application.
In edit mode some buttons should have a lower opacity.
A boolean variable stores if the edit mode is active. This variable is passed down to its childs using props. If I now change the editMode in the parents state, the childs are not being rerendered.
Parentclass:
export default class Parentclass extends Component{
constructor(props){
super(props);
this.state = {
editMode: false,
};
}
render(){
return(
<View>
<EditButtonClass onEditPress={() => this.editButtonPress()}/>
<View>
<Subclass editMode={this.state.editMode}/>
</View>
</View>
);
}
editButtonPress(){
this.setState({editMode: true})
}
}
Subclass:
export default class Subclass extends Component{
render(){
return(
<View>
<Finalsubclass editMode={this.props.editMode}/>
</View>
);
}
}
Final subclass:
export default class Finalsubclass extends Component{
createStyle(){
return{
opacity: this.props.editMode ? 0.5 : 1,
}
}
render(){
return(
<TouchableOpacity style={this.createStyle()}/>
);
}
}
The button:
<TouchableOpacity onPress={() => this.props.onEditPress()}>
<Image source={require('../res/edit-button.png')} style=styles.editButton}/>
</TouchableOpacity>
The editMode in props does change. If I click on one of the buttons they're getting brighter. But not directly if I enable editmode.
Whats the best way to achieve a full rerendering?
you can user react lifecycle to re-render component
https://reactjs.org/docs/react-component.html
and for above issue you can use
componentWillReceiveProps(nextProps) {
...
}
The solution was to build a View around the TouchableOpacity and applying the styles to the view.
As componentWillReceiveProps is deprecated, i would suggest using componentDidUpdate.
To answer the question in your comment, you need to check the prevProps with the new ones to not get an infinite loop.
For example:
componentDidUpdate = (prevProps) => {
if(prevProps!==this.props){ /if the previous props are different from the current props
//do what you need
}
}
As it is an object, if you need to only check a single variable you can simply do:
if (prevProps.foo !== this.props.foo) {
//do what you need
}

Material UI TextField React Component Conditional style don't trigger textField render

React Component :
class Info extends Component {
constructor() {
this.state = {
editAccount: false
}
this.changeTrue = this.changeTrue.bind(this);
this.changeFalse = this.changeFalse.bind(this);
}
changeTrue() {
this.setState({ediAccount: true}
}
changeFalse() {
this.setState({ediAccount: false}
}
render() {
const specific_style = this.state.editAccount ? { background: 'red'} : { background : 'yellow' }
return (
<div>
<TextField
id='first_name'
inputStyle={ specific_style}
value={this.state.first_name}
/>
<button onClick={this.changeTrue}>Click True</button>
<button onClick={this.changeFalse}>Click False</button>
</div>
)
}
}
Having this component and editAccount having the state changed doesn't rerender apply the style changes? Doesn't rerender the TextField ? Anybody knows why ?
State Updates May Be Asynchronous
React may batch multiple setState()
calls into a single update for performance.
Because this.props and this.state may be updated asynchronously, you
should not rely on their values for calculating the next state.
When updating the state based on the current state always use a callback in the call to setState(). The callback gets the previous state and returns the next state. This is because react may batch multiple calls to setState() thus not using a callback will override previous calls:
this.setState(prevState => ({editAccount: !prevState.editAccount)});
Also in your object that contains the styles you used variables (which you did not define) instead of strings:
const specific_style = this.state.editAccount ? { background: red /* red is not defined*/} : { background : yellow /* same here */ };
It should probably be:
const specific_style = this.state.editAccount ? { background: 'red' } : { background : 'yellow' };
Objects can't be written like css classes.
The fully working code has to look about like this:
class Info extends Component {
constructor(props) {
super(props);
this.state = {
editAccount: false
};
this.changeStyle = this.changeStyle.bind(this);
}
changeStyle() {
this.setState(state => ({editAccount: !state.editAccount}));
}
render() {
const specific_style = this.state.editAccount ? { background: 'red' } : { background: 'yellow' };
return (
<div>
<TextField
id="first_name"
inputStyle={specific_style}
/>
<button onClick={this.changeStyle}>Toggle red/yellow</button>
</div>
);
}
}
See this working codesandbox example.
It appears you forgot to put '<' and '/>' within the return of your render function. Two of us made edits to resolve this but perhaps thats also the issue
You may need to use a lifecycle method like componentWillReceiveProps to force a re-render. Also - format your code
Where / How is editAccount defined ? It should come from the state or the props to trigger the re-render.
If the render() method isn't affected by the props / state changes, it isn't triggered.

React Navigation: How to update navigation title for parent, when value comes from redux and gets updated in child?

I'm using react-navigation and have a StackNavigator with a ParentScreen and a ChildScreen.
Both screens have the same navigation bar with a dynamic value from redux. Implemented like described in Issue #313
This works as expected. When I'm in DetailScreen and I update the value for the count variable, it also updates the value in the navigation bar.
Problem is, if I go back to the parent scene, there is still the old value in the navigation bar. It doesn't update to the current value in redux store.
Child
Parent (when I go back)
ChildScreen
class ChildScreen extends Component {
static navigationOptions = {
title: ({ state }) => `Total: ${state.params && state.params.count ? state.params.count : ''}`
};
componentWillReceiveProps(nextProps) {
if (nextProps.count != this.props.count) {
this.props.navigation.setParams({ count: nextProps.count });
}
}
render() {
return (
<View>
<Button onPress={() => this.props.increment()} title="Increment" />
</View>
);
}
}
ParentScreen
class ParentScreen extends Component {
static navigationOptions = {
title: ({ state }) => `Total: ${state.params && state.params.count ? state.params.count : ''}`
};
}
Any advice?
My advice:
Make sure that ParentScreen is connected through react-redux connect function.
If you want the title of ParentScreen to get updated automatically when the state of the store changes, connecting it won't be enough. You will have to use the componentWillReceiveProps like you are doing in the ChildScreen Component.
Bonus: you could create a Higher Order Component for encapsulating that behaviour, like this:
const withTotalTitle = Component => props => {
class TotalTitle extends Component {
static navigationOptions = {
title: ({ state }) => `Total: ${state.params && state.params.count ? state.params.count : ''}`
};
componentWillReceiveProps(nextProps) {
if (nextProps.count != this.props.count) {
this.props.navigation.setParams({ count: nextProps.count });
}
}
render() {
return (
<Component {...props}/>
);
}
}
return connect(state => { count: state.total })(TotalTitle); // update this (I have no idea what the structure your state looks like)
};
And then you could use it like this:
const ChildScreen = withTotalTitle(({ increment }) => (
<View>
<Button onPress={() => increment()} title="Increment" />
</View>
));
const ParentScreen = withTotalTitle(() => (
<View>
<Text>Whatever ParentScreen is supposed to render.</Text>
</View>
));
OP, this is likely to be a problem with your redux implementation. Are you familiar with how redux implements its store? I see no mention here which means it is likely that your increment function is merely updating the child component's state instead of dispatching actions and reducers. Please have a look at a proper redux implementation like this one: https://onsen.io/blog/react-state-management-redux-store/
Have a common reducer for both parent and child. That way all the components(parent and child in your case) will get notified when the state changes.
Write a connect function for both parent and child. You'll receive the updated state in componentWillReceiveProps method. Use it as you please.
Hope it will help.
You need to use props in order to pass the incremented value from child to parent component.
find the article below. It has a great example of communications between parent and child components.
http://andrewhfarmer.com/component-communication/
Thanks

How to access this.setstate in onShouldStartLoadWithRequest() of a WebView in React Native?

I'm really struggling to understand how to read and set this.state inside of functions called by WebView when doing specific operations. My end goal is to:
Show a activity indicator when the user clicks a link inside the webview
Perform certain actions based on the URL the user is clicking on
I'm very new to React, but from what I've learned, I should use () => function to bind this from the main object to be accessible inside the function.
This works on onLoad={(e) => this._loading('onLoad Complete')} and I can update the state when the page loaded the first time.
If I use onShouldStartLoadWithRequest={this._onShouldStartLoadWithRequest} I can see that it works and my console.warn() is shown on screen. this.state is of course not available.
However if I change it to onShouldStartLoadWithRequest={() => this._onShouldStartLoadWithRequest} the function doesn't seem to be executed at all, and neither this.state (commented in the code below) or console.warn() is run.
Any help is appreciated!
import React, { Component} from 'react';
import {Text,View,WebView} from 'react-native';
class Question extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
debug: 'Debug header'
};
}
render() {
return (
<View style={{flex:1, marginTop:20}}>
<Text style={{backgroundColor: '#f9f', padding: 5}}>{this.state.debug}</Text>
<WebView
source={{uri: 'http://stackoverflow.com/'}}
renderLoading={this._renderLoading}
startInLoadingState={true}
javaScriptEnabled={true}
onShouldStartLoadWithRequest={this._onShouldStartLoadWithRequest}
onNavigationStateChange = {this._onShouldStartLoadWithRequest}
onLoad={(e) => this._loading('onLoad Complete')}
/>
</View>
);
}
_loading(text) {
this.setState({debug: text});
}
_renderLoading() {
return (
<Text style={{backgroundColor: '#ff0', padding: 5}}>_renderLoading</Text>
)
}
_onShouldStartLoadWithRequest(e) {
// If I call this with this._onShouldStartLoadWithRequest in the WebView props, I get "this.setState is not a function"
// But if I call it with () => this._onShouldStartLoadWithRequest it's not executed at all,
// and console.warn() isn't run
//this.setState({debug: e.url});
console.warn(e.url);
return true;
}
}
module.exports = Question;
To access correct this (class context) inside _onShouldStartLoadWithRequest, you need to bind it with class context, after binding whenever this method will get called this keyword inside it will point to react class.
Like this:
onShouldStartLoadWithRequest={this._onShouldStartLoadWithRequest.bind(this)}
or use arrow function like this:
onShouldStartLoadWithRequest={this._onShouldStartLoadWithRequest}
_onShouldStartLoadWithRequest = (e) => {...}
Or like this:
onShouldStartLoadWithRequest={(e) => this._onShouldStartLoadWithRequest(e)}
Check this answer for more details: Why is JavaScript bind() necessary?

react-native component lifecycle methods not firing on navigation

I am having an issue where I setState in multiple components based on the same key in AsyncStorage. Since the state is set in componentDidMount, and these components don't necessarily unmount and mount on navigation, the state value and the AsyncStorage value can get out of sync.
Here is the simplest example I could make.
Component A
A just sets up the navigation and app.
var React = require('react-native');
var B = require('./B');
var {
AppRegistry,
Navigator
} = React;
var A = React.createClass({
render() {
return (
<Navigator
initialRoute={{
component: B
}}
renderScene={(route, navigator) => {
return <route.component navigator={navigator} />;
}} />
);
}
});
AppRegistry.registerComponent('A', () => A);
Component B
B reads from AsyncStorage on mount, and then sets to state.
var React = require('react-native');
var C = require('./C');
var {
AsyncStorage,
View,
Text,
TouchableHighlight
} = React;
var B = React.createClass({
componentDidMount() {
AsyncStorage.getItem('some-identifier').then(value => {
this.setState({
isPresent: value !== null
});
});
},
getInitialState() {
return {
isPresent: false
};
},
goToC() {
this.props.navigator.push({
component: C
});
},
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>
{this.state.isPresent
? 'Value is present'
: 'Value is not present'}
</Text>
<TouchableHighlight onPress={this.goToC}>
<Text>Click to go to C</Text>
</TouchableHighlight>
</View>
);
}
});
module.exports = B;
Component C
C reads the same value from AsyncStorage as B, but allows you to change the value. Changing toggles both the value in state and in AsyncStorage.
var React = require('react-native');
var {
AsyncStorage,
View,
Text,
TouchableHighlight
} = React;
var C = React.createClass({
componentDidMount() {
AsyncStorage.getItem('some-identifier').then(value => {
this.setState({
isPresent: value !== null
});
});
},
getInitialState() {
return {
isPresent: false
};
},
toggle() {
if (this.state.isPresent) {
AsyncStorage.removeItem('some-identifier').then(() => {
this.setState({
isPresent: false
});
})
} else {
AsyncStorage.setItem('some-identifier', 'some-value').then(() => {
this.setState({
isPresent: true
});
});
}
},
goToB() {
this.props.navigator.pop();
},
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>
{this.state.isPresent
? 'Value is present'
: 'Value is not present'}
</Text>
<TouchableHighlight onPress={this.toggle}>
<Text>Click to toggle</Text>
</TouchableHighlight>
<TouchableHighlight onPress={this.goToB}>
<Text>Click to go back</Text>
</TouchableHighlight>
</View>
);
}
});
module.exports = C;
If you toggle in C and then return to B, the state in B and value in AsyncStorage are now out of sync. As far as I can tell, navigator.pop() does not trigger any component lifecycle functions I can use to tell B to refresh the value.
One solution I am aware of, but isn't ideal, is to make B's state a prop to C, and give C a callback prop to toggle it. That would work well if B and C would always be directly parent and child, but in a real app, the navigation hierarchy could be much deeper.
Is there anyway to trigger a function on a component after a navigation event, or something else that I'm missing?
Ran into the same issue as you. I hope this gets changed, or we get an extra event on components to listen to (componentDidRenderFromRoute) or something like that. Anyways, how I solved it was keeping my parent component in scope, so the child nav bar can call a method on the component. I'm using: https://github.com/Kureev/react-native-navbar, but it's simply a wrapper around Navigator:
class ProjectList extends Component {
_onChange(project) {
this.props.navigator.push({
component: Project,
props: { project: project },
navigationBar: (<NavigationBar
title={project.title}
titleColor="#000000"
style={appStyles.navigator}
customPrev={<CustomPrev onPress={() => {
this.props.navigator.pop();
this._sub();
}} />}
/>)
});
}
}
I'm pushing a project component with prop data, and attached my navigation bar component. The customPrev is what the react-native-navbar will replace with its default. So in its on press, i invoke the pop, and call the _sub method on my ProjectList instance.
I think the solution to that should be wrapper around the AsyncStorage and possibly using "flux" architecture. https://github.com/facebook/flux with the help of Dispatcher and Event Emitters - very similar to flux chat example: https://github.com/facebook/flux/tree/master/examples/flux-chat
First and most important. As noted in AsyncStorage docs: https://facebook.github.io/react-native/docs/asyncstorage.html
It is recommended that you use an abstraction on top of AsyncStorage
instead of AsyncStorage directly for anything more than light usage
since it operates globally.
So I believe you should build your own specific "domain" storage which will wrap the generic AsyncStorage and will do the following (see storages in the chat example):
expose specific methods (properties maybe?) for changing the values (any change should trigger "change" events after async change finishes)
expose specific methods (properties maybe?) for reading the values (those could become properties read synchronously as long as the domain storage caches the values after the async change finishes)
expose a "register for change" method (so that components that need to respond to change can register)
in such "change" event handler the component's state should be set as read from the storage (reading the property)
last but not least - I think it's best if following react's patterns, you make changes to the storage's through Dispatcher (part of flux). So rather than components calling the "change" method directly to the "domain storage", they generate "actions" and then the "domain" storage should handle the actions by updating it's stored values (and triggering change events consequently)
That might seem like an overkill first, but It solves a number of problems (including cascading updates and the like - which will be apparent when the app becomes bigger - and it introduces some reasonable abstractions that seem to make sense. You could probably to just points 1-4 without introducing the dispatcher as well - should still work but can later lead to the problems described by Facebook (read the flux docs for more details).
1) The main problem here is in your architecture - you need to create some wrapper around AsyncStorage that also generates events when some value is changed, example of class interface is:
class Storage extends EventEmitter {
get(key) { ... }
set(key, value) { ... }
}
In componentWillMount:
storage.on('someValueChanged', this.onChanged);
In componentWillUnmount:
storage.removeListener('someValueChanged', this.onChanged);
2) Architecture problem can be also fixed by using for example redux + react-redux, with it's global app state and automatic re-rendering when it is changed.
3) Other way (not event-based, so not perfect) is to add custom lifecycle methods like componentDidAppear and componentDidDissapear. Here is example BaseComponent class:
import React, { Component } from 'react';
export default class BaseComponent extends Component {
constructor(props) {
super(props);
this.appeared = false;
}
componentWillMount() {
this.route = this.props.navigator.navigationContext.currentRoute;
console.log('componentWillMount', this.route.name);
this.didFocusSubscription = this.props.navigator.navigationContext.addListener('didfocus', event => {
if (this.route === event.data.route) {
this.appeared = true;
this.componentDidAppear();
} else if (this.appeared) {
this.appeared = false;
this.componentDidDisappear();
}
});
}
componentDidMount() {
console.log('componentDidMount', this.route.name);
}
componentWillUnmount() {
console.log('componentWillUnmount', this.route.name);
this.didFocusSubscription.remove();
this.componentDidDisappear();
}
componentDidAppear() {
console.log('componentDidAppear', this.route.name);
}
componentDidDisappear() {
console.log('componentDidDisappear', this.route.name);
}
}
So just extend from that component and override componentDidAppear method (Don't forget about OOP and call super implementation inside: super.componentdDidAppear()).
If you use NavigatorIOS then it can pass an underlying navigator to each child component. That has a couple of events you can use from within those components:
onDidFocus function
Will be called with the new route of each scene
after the transition is complete or after the initial mounting
onItemRef function
Will be called with (ref, indexInStack, route)
when the scene ref changes
onWillFocus function
Will emit the target route upon mounting and
before each nav transition
https://facebook.github.io/react-native/docs/navigator.html#content
My solution is trying to add my custom life cycle for component.
this._navigator.addListener('didfocus', (event) => {
let component = event.target.currentRoute.scene;
if (component.getWrappedInstance !== undefined) {
// If component is wrapped by react-redux
component = component.getWrappedInstance();
}
if (component.componentDidFocusByNavigator !== undefined &&
typeof(component.componentDidFocusByNavigator) === 'function') {
component.componentDidFocusByNavigator();
}
});
Then you can add componentDidFocusByNavigator() in your component to do something.

Resources