How to implement focus/blur response in a custom react-native TextInput - react-native

I implemented a custom react-native TextInput backed by a native library. It's working pretty well except that when I tap outside of the textfield, it doesn't blur automatically and the keyboard doesn't disappear. I also tried with Keyboard.dismiss(), it doesn't work either. I looked at the 'official' TextInput implementation to replicate it without any success.
I added this code in my custom implementation (componentDidMount)
if (this.context.focusEmitter) {
this._focusSubscription = this.context.focusEmitter.addListener(
'focus',
el => {
if (this === el) {
this.requestAnimationFrame(this.focus);
} else if (this.isFocused()) {
this.blur();
}
},
);
if (this.props.autoFocus) {
this.context.onFocusRequested(this);
}
} else {
if (this.props.autoFocus) {
this.requestAnimationFrame(this.focus);
}
}
and I also defined the required contextTypes
static contextTypes = {
focusEmitter: PropTypes.instanceOf(EventEmitter)
}
code from TextInput
The problem I have is that the focusEmitter is undefined in the context and I have no idea from where it's provided in the context nor if it's actually the way it works for the regular TextInput. The only occurence of focusEmitter I could find in the react-native repo is in NavigatorIOS which I don't even use in my app.
Could anyone clarify this to me?

The simpler way to do what you want is to use Keyboard.dismiss() on a TouchableWithoutFeedback just like following example:
import {Keyboard} from 'react-native';
...
render(){
return(
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<View>
// Return everything here
<TextInput />
</View>
</TouchableWithoutFeedback>
)
}
So when you tap outside the input it will dismiss keyboard and blur the TextInput.

Related

react native webview navigation issue

I am making a test with react navigaton and webview , I have 2 screens , Home and Details , at details screen I am calling / opening a webpage inside webview , let's say that I am calling stackoverflow.com (Page A) , my problem is that when user click a link of the stackoverflow page and navigate and after wants to go back to the previous page (Page A) , it doesn't go , its going or navigating to the Home screen !!!
how can I let The user go back to the previous page. ?
that 's how I am calling the page
<WebView
javaScriptEnabled
source={{uri: 'https://stackoverflow.com/'}}
style={{marginTop: 20}}
/>
As we know built in back button is not provided in iOs but it is provided in android .
So for considering both platform there is two possibility.
Android.
-> For android you have to define BackHandler so here are the step.
import it like this.
import {BackHandler } from 'react-native'.
initialize backhandler inside the life cycle methods.
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
}
handleBackPress = () => {
if (this.state.canGoBack) {
this.refWeb.goBack();
}
else{
this.props.navigation.goBack(null)
}
return true;
}
define a userdefine variable canGoBack inside the status.
constructor(props) {
super(props)
this.state = {
canGoBack: false
}
}
create a method which detect the change in navigation of the webview and bind it with the web view.
onNavigationStateChange(navState) {
this.setState({
canGoBack: navState.canGoBack
});
}
Bind it like this.
<WebView
ref={(myWeb) => this.refWeb = myWeb}
onNavigationStateChange={this.onNavigationStateChange.bind(this)}
source={{ uri: 'https://stackoverflow.com/questions/51712310/react-
native-webview-navigation-issue' }} />
And thsts it you are ready to go..
iOs
For iOs you didn't have to bother too much.
Create a button for back press above the webview or according to your design logic
Follow the above webview and navigation logic . forgot about the backhandler and set this code inside the onPress() method of your created button of backpress
if (this.state.canGoBack) {
this.refWeb.goBack();
}else{
this.props.navigation.goBack(null)
}
Note : Here I use stackNavigator for screen navigation so i used this.props.navigation.goBack(null) this code. if you didn't use it then dont consider this code and replace with your feasible navigator code in else condition
Thankyou..

react-native scrollView - scrollToEnd - on Android

I'm trying to call a function that will fire upon onFoucs on TextInput that will scroll the scrollView all the way down (using scrollToEnd())
so this is my class component
class MyCMP extends Component {
constructor(props) {
super(props);
this.onInputFocus = this.onInputFocus.bind(this);
}
onInputFocus() {
setTimeout(() => {
this.refs.scroll.scrollToEnd();
console.log('done scrolling');
}, 1);
}
render() {
return (
<View>
<ScrollView ref="scroll">
{ /* items */ }
</ScrollView>
<TextInput onFocus={this.onInputFocus} />
</View>
);
}
}
export default MyCMP;
the component above works and it does scroll but it takes a lot of time ... I'm using setTimeout because without it its just going down the screen without calculating the keybaord's height so it not scrolling down enough, even when I keep typing (and triggering that focus on the input) it still doesn't scroll all the way down.
I'm dealing with it some good hours now, I did set the windowSoftInputMode to adjustResize and I did went through some modules like react-native-keyboard-aware-scroll-view or react-native-auto-scroll but none of them really does the work as I need it.
any direction how to make it done the right way would be really appreciated. thanks!
Rather than using a setTimeout you use Keyboard API of react-native. You add an event listener for keyboard show and then scroll the view to end. You might need to create some logic on which input is focused if you have more than one input in your component but if you only have one you can just do it like the example below.
Another good thing to do is changing your refs to functional ones since string refs are considered as legacy and will be removed in future releases of react. More info here.
class MyCMP extends Component {
constructor(props) {
super(props);
this.scroll = null;
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
}
componentWillUnmount () {
this.keyboardDidShowListener.remove();
}
_keyboardDidShow() {
this.scroll.scrollToEnd();
}
render() {
return (
<View>
<ScrollView ref={(scroll) => {this.scroll = scroll;}}>
{ /* items */ }
</ScrollView>
<TextInput />
</View>
);
}
}
export default MyCMP;
If you have a large dataset React Native docs is telling you to go with FlatList.
To get it to scroll to bottom this is what worked for me
<FlatList
ref={ref => (this.scrollView = ref)}
onContentSizeChange={() => {
this.scrollView.scrollToEnd({ animated: true, index: -1 }, 200);
}}
/>

Changing Drawer left and right button image dynamically?

react-native-router-flux v3.37.0
react-native v0.42.0
I'm trying to update drawer navigation bar right image dynamically where I have used leftButtonImage, rightButtonImage, where once user read all the notification I want to change the button image.
I could not manage to re-render or update this button image, Is this feature not supported or is there something that I'm missing?
You can call Actions.refresh when you need to refresh the view, example:
Actions.refresh({key: 'profileView', renderRightButton: this.renderRightButton });
and also define renderRightButton:
renderRightButton() {
return (
<TouchableOpacity onPress={ console.log(this) } >
<Text>Logout</Text>
</TouchableOpacity>
)
}
and lastly don't forget to import Actions from react-native-router-flux
import {Actions} from 'react-native-router-flux';
You can re-render using props or states naturally.
Check the states you want, and apply image resource following the states.(or props)
let NotiImage = {
normal: require('../assets/image/notinormal.png');
new: require('../assets/image/new.png');
}
render() {
...
<Image source={ this.state.newNoti ? NotiImage.new : NotiImage.normal } />
...
}

Implement Hero animation like shoutem About extension

I try to implement the hero animation like in the shoutem About extension. Basically, I add animationName to NavigationBar and the Image like in the extension. I also had to add ScrollDriver because it would error-ed otherwise. But it seems the NavigationBar does not pass the driver down to its child components, so I still got this error. Is it possible to implement the hero animation like what was demonstrated here? https://medium.com/shoutem/declare-peace-with-react-native-animations-e947332fa9b1
Thanks,
import { ScrollDriver } from '#shoutem/animation';
getNavBarProps() {
const driver = new ScrollDriver();
return {
hasHistory: true,
driver: driver,
title: 'Title',
navigateBack: () => this.props.navigation.dispatch(NavigationActions.back()),
styleName: 'fade clear',
animationName: 'solidify',
};
}
render () {
const driver = new ScrollDriver();
return (
<Screen styleName=" paper">
<View style={{height:68}}>
<NavigationBar {...this.getNavBarProps()} />
</View>
<ScrollView style={styles.container}>
<Image
styleName="large"
source={require('../Images/spa2.jpg') }
defaultSource={require('../Images/image-fallback.png')}
driver={driver}
animationName="hero"
/>
...
I'm the author of the article, from you question, I'm not sure are you trying to create an extension on shoutem or you just want to recreate animation in any other React Native app.
If you are creating an extension or CardStack from #shoutem/ui/navigation, you don't event need to care for ScrollDriver. It would be pushed throught the context to the ScrollView (imported from #shoutem/ui) and NavigationBar (imported from #shoutem/ui/navigation).
If you are creating your own React Native project to be able to do it like in article I suggest the following. At the root component of your app:
import ScrollView from '#shoutem/ui';
class App extends Component {
...
render() {
return (
<ScrollView.DriverProvider>
<App />
</ScrollView.DriverProvider>
);
}
}
Then you don't have to take care of initialization of ScrollDriver on each screen, if you use our components and a ScrollView it will push the driver where it needs to be. :) So your screen at the end would look like this:
import {
ScrollView,
NavigationBar,
Image
} from '#shoutem/ui';
class MyScreen extends Class {
render() {
return (
<Screen>
<NavigationBar animationName="solidify" />
<ScrollView>
<Image animationName="hero" />
</ScrollView>
</Screen>
);
}
}
The whole working example is here https://github.com/shoutem/ui/tree/develop/examples/RestaurantsApp/app

React native Android Home always starts a splash screen

Using navigator I hit home from my react native android app and then return to the app and it always starts at the initial route which is my splash screen. Is there away to keep the component that was in view last the component that will be in view when the app re-opens?
class AwesomeProject extends Component {
render() {
return (
<Navigator
style={{ flex:1 }}
initialRoute={{ id: 'SplashPage' }}
renderScene={ this.renderScene }
/>
);
}
renderScene(route, navigator) {
if (route.id === 'SplashPage') {
return (
<SplashPage
navigator={navigator} {...route.passProps}
/>
);
}else if(route.id === 'HomePage'){
return (
<HomePage
navigator={navigator} {...route.passProps}
/>
);
}else if(route.id === 'ListViewPage'){
return (
<ListViewPage
navigator={navigator} {...route.passProps}
/>
);
}
}
}
You need to add the following code to /android/app/src/main/java/com//MainActivity.java. so, that it maintains the stacks of application.
#Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
if you dont achieve your answer from above please follow reference as below:
https://facebook.github.io/react-native/docs/native-modules-android.html
and in last of above reference there is lifecycle event for application in react-native. So, follow same strategy like native android onPause/onDestroy/onStop method and please solve your problem.
can you make sure you app is live when you press home?
My first suggestion is not to use splashscreen as a scene. If you use that in such a way it is not splashscreen rather a component. Use the native java code as mentioned in the links below to get your problem solved like charm.
https://github.com/react-native-component/react-native-smart-splash-screen
with this there are certain import errors which can be fixed looking at the issues section or check my code in github which contains the perfect use of the splashscreen module.
https://github.com/UjjwalNepal/Dental
Hope this helps.
Thank you