react-native - TouchableHighlight: Remove highlighting after onPress? - react-native

I am developing a simple react-native app and am encountering an issue on TouchableHighlight:
When pressing the TouchableHighlight, a new screen is displayed (using StackNavigator from react-navigation). After pressing the back-button and returning to the original screen, the TouchableHighlight still has a black background-color - meaning, that it is still highlighted.
My questions are:
Is there a way to manually deactivate the highlighting of a TouchableHighlight-component? That way I could disable the highlighting after onPress has run.
What could be possible reasons to why the TouchableHighlight stays highlighted? I am using it on other parts of my app without navigation, and I could imagine that it has to do with that.
The TouchableHighlight exists within a FlatList. The renderItems-method looks like the following:
let handlePress = () => {
this.props.navigation.navigate('DetailsScreen');
};
return <TouchableHighlight
onPress={handlePress}>
<Text>Some Text</Text>
</TouchableHighlight>;
If you need/want any further information, please let me know. I've tested the code on android, using the Genymotion-emulator with Marshmallow.
Versions are:
node -v: 8.9.4
npm -v: 5.6.0
react-native-cli: 2.0.1
react-native: 0.54.2
react-navigation: 1.5.2
Build environment: Windows 10 64-bit
At this point, I'm quite certain that the error is somewhere in my code, as TouchableHighlight works correctly on other parts of my app, and it propably has to do with the navigation-call, but I was unable to pinpoint, why exactly. I've made sure that there are no exceptions or anything like that in my app, and that the onPress-method therefore finishes successfully.

You can replace Touchable Highlight with Touchable opacity and simply set activeOpactity prop with value 1. It will not highlight the press.
<TouchableOpacity activeOpacity={1}>....</TouchableOpacity>

After using the tip from #Kartiikeya and exchanging TouchableHighlight with TouchableOpacity and back to TouchableHighlight, it now works as expected:
Now, after onPress has been executed, the button (be it a TouchableOpacity or a TouchableHighlight) looses its effect.
I am not sure, why it works now. The obvious reason would be, that a recompilation of the source code fixed errors - but I recompiled it for writing the original question multiple times before, so that that cannot be an option. Other users I would suggest to clear any cache possible, and especially do the following steps:
Close and reopen the android emulator / restart your testing device
Restart the build PC
Recompile all source code
Check in your console for errors and/or exceptions (obviously)
Replace TouchableHighlight with TouchableOpacity, recompile, check if the error still exists - and if not, reexchange TouchableOpacity to TouchableHighlight

You can replace Touchable Highlight with Touchable opacity. It won't highlight the press.
return <TouchableOpacity
onPress={handlePress}>
<Text>Some Text</Text>
</TouchableOpacity >;

For me, i needed to disable the highlight effect after onLongPress has been fired. You can simply change the key of the touchable using a re-render when you want to remove it.
Here's an example:
<TouchableHighLight
onPress={this.pressRow}
style={styles.outerContainer}
onLongPress={() => this.setState({ onLongPressed: true })}
onPressOut={() => this.setState({ onLongPressed: false })}
key={`long-pressed-${this.state.onLongPressed ? 'yes' : 'no'}`}>
<View style={styles.innerContainer}>
{rowText}
{rowIcon}
</View>
</TouchableHighLight>

Following Leonardo Lusoli's answer, there one thing you should also add is
useEffect(() => {
if(isLongPressed){
setIsLongPressed(false)
}
}, [isLongPressed])
This step is necessary because
when the first onLongPress event is fired it will set isLongPressed to true and thus changing the key the component is re-rendered and is identifies as a new component and previour event listners are discareded so the onPressOut will not be fired. So
when isLongPressed is set to true the component re-renders and then immediatietly we set it's value to false and thus we get the expected behaviour. Otherwise we will get the unexpected behaviour followed by one expected behaviour.

Related

Status bar doesnt respect 'barStyle' property

In React Native, using the following:
<StatusBar backgroundColor={config.colors.backgroundGray} barStyle="dark-content" />
works well. However when navigating to a different screen, even though the above is the only instance of StatusBar used in the entire app, the status bar style turns to what essentially is "light-content" on its own. Rendering the StatusBar component deeper in again seems to yield no results.
The backgroundColor is controllable however. Any ideas?
You can apply Statusbar's own function to App.js.
App.js
import { StatusBar } from 'react-native';
StatusBar.setBarStyle('dark-content', true);
static setBarStyle(style: StatusBarStyle, [animated]: boolean)

react-native-webview avoid keyboard (iOS)

The react-native-webview has in my experience proved difficult to behave as I want around the keyboard on iOS. It doesn't automatically change it's height when the keyboard is shown and its contents gets concealed by the keyboard.
It also behaves strangely wrapped with the KeyboardAvoidingView. In my case it seems to adjust the content of the WebView too much, approximately twice the height of the keyboard. This same behavior appeared when I manually listened for the keyboard open/close events and adjusted the height of the WebView accordingly:
componentDidMount(){
Keyboard.addListener("keyboardWillShow", this.keyboardDidShow.bind(this));
Keyboard.addListener("keyboardWillHide", this.keyboardDidHide.bind(this));
}
componentWillUnmount(){
Keyboard.removeListener("keyboardWillShow", this.keyboardDidShow.bind(this));
Keyboard.removeListener("keyboardWillHide", this.keyboardDidHide.bind(this));
}
keyboardDidShow(event){
this.setState({
keyboardHeight: event.endCoordinates.height
});
}
keyboardDidHide(event){
this.setState({
keyboardHeight: 0
});
}
render(){
return (
<WebView
style={{flex: 1, maxHeight: Dimensions.get("window").height - this.state.keyboardHeight}}
/>
);
}
I've found a solution, not optimal, but a solution non the less. My answer is posted below.
As I couldn't find any discussions on this particular behavior and no solutions that worked for me, I worked my way through the props of the react-native-webview docs. What finally worked for me in version 0.59.9 of React Native and version 5.11.0 of React Native WebView was as described above, manually setting the height of the WebView in the keyboard event listeners and setting the WebView prop useWebKit={false}.
Unfortunately this means that on the native side of the WebView, it's now using UIWebView which is deprecated and will in a future release be deleted.
Either way, this is what I'm rolling with and simply wanted to share my findings in case anyone finds themselves with the same issue.

Scrolling to the bottom of a ScrollView on initial load

I have a large long image with a few inputs at the bottom in my react native view. When the view loads I want it to be "scrolled" to the bottom of the page -- all the examples I can find online are triggered because of some event that the user does.
I want to call scrollToEnd() but I'm not sure where in the lifecycle the ref will actually be set -- anyone have ideas?
Use scrollToEnd this way. It will take to the bottom of ScrollView
<ScrollView
ref={ref => this.scrollView = ref}
onContentSizeChange={(contentWidth, contentHeight)=>{
this.scrollView.scrollToEnd({animated: true});
}}>
I am not clear with your question but
With react-native Image component we have onLoad prop. I think this is what you are looking for.
try something like:
<Image source={{uri...}} onLoad={(e)=>this.handleImageLoaded(e)}/>
then inside handleImageLoaded method you can use scrollToEnd() with some ref as per your code.
also there are other useful props like onLoadStart/End check here
https://facebook.github.io/react-native/docs/image
Or if you are just waiting for the view to render then to scroll
for that I think componentDidAppear() lifecycle method, if using react-native -navigation by wix
or with react-navigation
willFocus, willBlur, didFocus and didBlur events for the component render cycle.. explained here
https://reactnavigation.org/docs/en/navigation-prop.html#addlistener-subscribe-to-updates-to-navigation-lifecycle

How to clear input in SlideTextInput (custom TextInput component)?

and of course sorry if the question is somewhat dumb.
In the app I'm developing a user should be able to swipe on the TextInput. Since TextInput only listens to taps I used this gist: https://gist.github.com/MikeShi42/87b65984f0a31e38d553cc056fcda017
(BTW #Michael Shi thanks a ton)
However, once I changed TextInput to SlideTextInput the Clear button ceased to work.
clearInput() {
this.setState({text: ''});
}
render() {
return (
<Button name='clear' action={this.clearInput} />
<SlideTextInput
style={styles.input}
ref='input'
onChangeText={(text) => this.setState({text: text})}
placeholder={this.state.placeholder}
value={this.state.text}
multiline={true}
returnKeyType='done'
blurOnSubmit={true} />
)
}
I also tried this.refs.input.setNativeProps({text: ''}); instead of just passing a new value prop (that should be — and was — sufficient for normal TextInput), and calling forceUpdate(), but again to no avail. I don't see much changes in SlideTextInput.js compared to the original TextInput component, but I must be missing something that would explain such bad behaviour?
UPD: the answer was pretty simple in the end. Instead of linking the component to its native counterpart (ref={this._setNativeRef}) like original TextInput does, SlideTextInput has it ref'ed to a string (ref="input"). I changed it back and voila.
Looking at the code it seems that the value props is not being sent to the original TextInput. It is extending the TextInput but it is returning another component without sending the value prop.
Try:
this.refs.input.setText('');
The answer was pretty simple in the end. Instead of linking the component to its native counterpart (ref={this._setNativeRef}) like original TextInput does, SlideTextInput has it ref'ed to a string (ref="input") (it's not about props in my code it's about SlideTextInput.js file itself). I changed it back and voila.

TouchableHighlight and TouchableOpacity get highlighted on render()

I experience a behaviour where TouchableHighlight and TouchableOpacity reacts visually upon render (onPress is not being called).
One thing is that it looks just a little strange, when I enter the page and my button make a small "blink". This is strange but tolerable. The more frustrating part is that if I alter state for the parent component and thus invoke a re-render(), the button will "blink" again, making all buttons blink whenever I alter state.
Pushing the buttons alters page state, and thus pushing a button makes both buttons "blink".
I use react-redux, but this should not affect this behaviour.
The code below is just for illustration.
render()
{
return(
<View>
<ToucableHightlight> //Click here changes state
<Content/>
</ToucableHightlight>
<ToucableHightlight> //Click here changes state
<Content/>
</ToucableHightlight>
<View>
);
}
Add activeOpacity in TouchableOpacity and it will force to not blink.
<TouchableOpacity style={styles.opecity} activeOpacity={1}>
I solved the problem. Earlier during my render function i defined the "Content"-components, resulting in new (but alike) components being defined during each update. Placing the definitions of "Content" outside of the render function fixed it, so that the components no longer flashes when the page is re-rendered.
This explains why my component was rendered as a new component upon each render in the parent component, but it does not explain why a TouchableHighlight blinks during its initial render.
Buttons blinking during initial render is acceptable to me - buttons blinking upon any state-change is not.
So I am sufficiently happy now.
Not sure if it's because I'm running a later version, but I found this blinking behavior happens only on the first click.
My solution was putting the code that triggers rerendering in a setTimeout
<TouchableOpacity
onPress={function() {
setTimeout(function() {
_this.setState({myState: 'someValue'})
});
}}
>