TextInput auto scroll to bottom in multiline in react native - android

I have a TextInput component, and i want to make text visible when keyboard is on, by default, android will have this, but i don't know why the multiline TextInput just scroll down to the bottom of the text exact the same behavior of single line ( also the cursor at the lastest text)
Here is the code of it
<SafeAreaView style={{ margin: spacingWidth[3], flex: 1 }}>
<View row centerV style={HEADER}>. //just set margin
<TouchableOpacity onPress={() => nav.goBack()}>
<BackArrow name="arrowleft" size={onePercentWidth * 6} />
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
editAndSaveFirebase();
nav.goBack();
dispatch(switchReloadOn());
dispatch(fetchNote(userInfo.email)).then(() =>
dispatch(switchReloadOff())
);
// saveAndNavBack();
}}
>
<Text style={SAVE_NOTE_BT}>Save</Text>
</TouchableOpacity>
</View>
<TextInput
onChangeText={(text) => setNoteHeader(text)}
value={noteHeader}
placeholder="Meaningful header"
style={HEADER_INPUT}
/>
<ScrollView
showsVerticalScrollIndicator={false}
style={{
flex: 1,
}}
contentContainerStyle={{
flexGrow: 1,
}}
> ====> the problem here
<TextInput
scrollEnabled={false}
textAlignVertical={Platform.OS === "android" ? "top" : ""}
onChangeText={(text) => setNoteEdit(text)}
placeholder="Type your secret here..."
value={noteEdit}
multiline
style={NOTE_INPUT}. // i just set the fontSize
/>
</ScrollView>
</SafeAreaView>
);
Here is the behavior i talked about

You should set scrollEnabled: false only for iOS. If you still don't reach the expected behaviour, you can pass ref to the scrollView and scrollToEnd on TextInput focus.
const scrollViewRef = useRef<ScrollView>(null)
const handleInputFocus = () => {
if (isAndroid) {
setTimeout(() => scrollViewRef.current?.scrollToEnd({ animated: true }), 200)
}
}
<ScrollView ref={scrollViewRef}>
<TextInput
{...otherInputProps}
onFocus={handleInputFocus}
scrollEnabled={isAndroid}
/>
</ScrollView>

Related

I have added a picture on bottom. Now my keyboard is not opening

I have added a picture on the bottom of the mobile screen with style as:
bottomView: {
position: 'absolute',
bottom: 0,
},
Above this picture, I have my sign-in form, but because the picture is at the absolute position, it is not letting the keyboard open. I don't want to make this picture relative as it will disturb the picture. Can anyone help me in such a way that I want to keep the picture on the bottom too but want to open the keyboard as well.
Complete code is:
import React from "react";
import { Image, StyleSheet, Text, View ,TextInput,KeyboardAvoidingView} from "react-native";
import Authentication_Button from "./Authentication_Button";
import { SocialIcon } from 'react-native-elements'
const Login = () => {
const [email, setEmail] = React.useState('');
const [password, setPassword] = React.useState('');
return(
<KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container} enabled>
{/* <View style={styles.container}> */}
<Image source={require('./assets/Logo.png')} style={styles.logo}/>
<TextInput
label="Email"
value={email}
onChangeText={email => setEmail(email)}
style={styles.TXT_INPUT}
placeholder="Email"
/>
<TextInput
label="Password"
value={password}
onChangeText={password => setPassword(password)}
style={styles.TXT_INPUT}
placeholder="Password"
/>
<View style={styles.auth}>
<Authentication_Button title={"Login"} backGroundColor={"#2c88d1"} textColor = {"#FFFFFF"} borderColor={"#2c88d1"}/>
<Authentication_Button title={"Signup"} backGroundColor={"#FFFFFF"} textColor = {"#2c88d1"} borderColor={"#2c88d1"}/>
</View>
<Text>- OR -</Text>
<Text>Sign in with </Text>
<SocialIcon
raised={true}
type='google'
style={{backgroundColor:"#2c88d1"}}
/>
<KeyboardAvoidingView style={styles.bottomView}>
<Image source={require('./assets/footLogin.png')} />
</KeyboardAvoidingView>
{/* </View> */}
</KeyboardAvoidingView>
)
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor:"#effdfe",
justifyContent:"center",
alignItems:"center",
padding:20
},
logo :{
width:150,
height:150,
resizeMode:'cover'
},
TXT_INPUT:{
marginBottom:10,
marginTop:10,
borderRadius:12,
borderWidth:1.4,
width:"85%",
paddingVertical:14,
backgroundColor:"#ffffff",
color:"#000000",
fontSize:18
},
auth:{
marginTop:10,
marginBottom:10,
width:"85%",
},
bottomView: {
marginTop:'5%',
position: 'absolute', //Here is the trick
bottom: 1, //Here is the trick
},
});
export default Login;
You can use KeyboardAvoidingView as a parent view. It will help you either your internal button or view is an absolute position
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container}
>
</KeyboardAvoidingView>
So the issue has been resolved. The issue was that the footer image was basically on top ofthe text input fields so as soon I changed the positions, it started to work!

React Native text field inside webview got overlap at last textfield

in my react native app i have one webview and inside that i have 4 textfield on that so when i focus last text input at that time keyboard is overlapping last text field not scroll automatically below is m code
render() {
return (
<View style={styles.mainView} >
<WebView
ref={r => this.webview = r}
style={{width:globals.screenWidth, height:globals.screenHeight}}
bounces={false}
style={{ flex: 1 }}
startInLoadingState
scalesPageToFit
javaScriptEnabledAndroid={true}
javaScriptEnabled={true}
domStorageEnabled = {true}
onNavigationStateChange={this.handleNavigationStateChange}
onLoadStart={() => {
}}
onLoadEnd={() => {
}}
source={{uri: this.state.url}}
onError={(error) => this.onError()}
/>
</View>
);
}
So any idea how can i solve this your all suggestions are appreciable
try to use https://github.com/APSL/react-native-keyboard-aware-scroll-view instead of View component.

React native onStartShouldSetResponder parameter not working for AutoCompeletInput plugin

I am using plugin for Autocomplete Input. I have placed this component in Scrollview. It's other behaviour is fine like displaying suggestion list in popup with our custom design.
Referred Plugin:- Plugin
But onStartShouldSetResponder{()=>true} not working.
Because of that I am unable to scroll my suggestion list.
Here is my implemented code =>
<ScrollView keyboardShouldPersistTaps='always' style={[commonstyles.mainContainer,styles.mainContainer,{marginBottom:20}]}>
<View style={{width:width-30,height:45}}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
hideResults={false}
containerStyle={{flex: 1,left: 10,position: 'absolute',right: 10,top: 0,zIndex: 1}}
data={films.length === 1 && comp(query, films[0].name) ? [] : films}
defaultValue={query}
onChangeText={text => this.setState({ query: text })}
placeholder="Select Contact"
renderItem={({ id,name }) => (
<TouchableOpacity onStartShouldSetResponder={()=>{return true;}} activeOpacity={1} onPress={() => this.setState({ query: name })}>
<Text style={{fontSize:Global.DESCRIPTION_FONT_SIZE,color:Global.APP_BLACK_COLOR,borderBottomWidth:0.5,borderColor:Global.APP_BLACK_COLOR,padding:5}}>
{id} {name}
</Text>
</TouchableOpacity>
)}
/>
</View>
</Scrollview>
Please let me know if I am doing something wrong.
Also I am unable to understand implementation of onStartShouldSetResponder() function.
Suggest Autocomplete input example in react native which work like Android AutoCompleteTexview component.
Add scrollEnabled parameter to your Scrollview.
Try with below code
<ScrollView scrollEnabled={this.state.enableScrollViewScroll} keyboardShouldPersistTaps='always' style={[commonstyles.mainContainer,styles.mainContainer,{marginBottom:20}]}>
<View style={{width:width-30,height:45}}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
hideResults={false}
onStartShouldSetResponderCapture={() => {
var self=this;
this.setState({ enableScrollViewScroll: false });
console.log("Here==>",self.state.enableScrollViewScroll);
}}
containerStyle={{flex: 1,left: 10,position: 'absolute',right: 10,top: 0,zIndex: 1}}
data={films.length === 1 && comp(query, films[0].name) ? [] : films}
defaultValue={query}
onChangeText={text => this.setState({ query: text })}
placeholder="Select Contact"
renderItem={({ id,name }) => (
<TouchableOpacity activeOpacity={1} onPress={() => this.setState({ query: name,enableScrollViewScroll:true })}>
<Text style= {{fontSize:Global.DESCRIPTION_FONT_SIZE,color:Global.APP_BLACK_COLOR,borderBottomWidth:0.5,borderColor:Global.APP_BLACK_COLOR,padding:5}}>
{id} {name}
</Text>
</TouchableOpacity>
)}
/>
</View>
</Scrollview>

Click event on words react native

I want to set different click listeners on different words of . Currently what i have is
<Text>Android iOS React Native<Text>
Now i want to know when user click on Android, iOS and React Native, i have to perform some analytics on that so need click listeners for seperate words.
Does any one have idea about it? I have checked this thread but i din't found it useful for my requirement.
Update
String i have given is just an example string, in real time i will be getting dynamic strings.
This is what i will be getting as dynamic string
{
"str":"Hi i am using React-Native, Earlier i was using Android and so on"
"tagWords":["React-Native","Android"]
}
And in output i want, "Hi i am using React-Native, Earlier i was using Android and so on"
with click event on "React-Native" and "Android". Is is possible?
The post you sent is the simplest way you can achieve the desired behavior. Sinse you need to have different listeners you need to implement different Text components.
Example
export default class App extends Component {
onTextPress(event, text) {
console.log(text);
}
render() {
return (
<View style={styles.container}>
<Text>
<Text onPress={(e) => this.onTextPress(e, 'Android')} style={styles.red}>{'Android '}</Text>
<Text onPress={(e) => this.onTextPress(e, 'iOS')} style={styles.purple}>{'iOS '}</Text>
<Text onPress={(e) => this.onTextPress(e, 'React Native')} style={styles.green}>{'React Native'}</Text>
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
red: {
fontSize: 20,
color: 'red'
},
purple: {
fontSize: 20,
color: 'purple'
},
green: {
fontSize: 20,
color: 'green'
}
});
Update 1 (Dynamic text)
render() {
const fixedString = 'I\'m a fixed string that slipleted';
const arrayOfStrings = ['These', 'are', 'strings', 'from', 'array'];
return (
<View style={styles.container}>
<Text style={styles.textContainer}>
{
fixedString.split(' ').map((str, index) => {
return (
<Text onPress={(e) => this.onTextPress(e, str)}>
{`${str}${index !== (fixedString.split(' ').lenght -1) && ' '}`}
</Text>
)
})
}
</Text>
<Text style={styles.textContainer}>
{
arrayOfStrings.map((str, index) => {
return (
<Text onPress={(e) => this.onTextPress(e, str)}>
{`${str}${index !== (arrayOfStrings.lenght -1) && ' '}`}
</Text>
)
})
}
</Text>
</View>
);
}
Update 2 (for example dynamic data)
removePunctuation = (text) => {
// this is a hack to remove comma from the text
// you may want to handle this different
return text.replace(/[.,\/#!$%\^&\*;:{}=\_`~()]/g,"");
}
render() {
const arrayOfObjects = [{
str: 'Hi i am using React-Native, Earlier i was using Android and so on',
tagWords: ['React-Native', 'Android']
}];
return (
<View style={styles.container}>
<Text style={styles.textContainer}>
{
arrayOfObjects.map((obj) => {
return obj.str.split(' ').map((s, index) => {
if ( obj.tagWords.indexOf(this.removePunctuation(s)) > -1 ) {
return (
<Text onPress={(e) => this.onTextPress(e, s)} style={styles.red}>
{`${s} ${index !== (obj.str.split(' ').lenght - 1) && ' '}`}
</Text>
)
} else return `${s} `;
})
})
}
</Text>
</View>
);
}
all you need to use is TouchableOpacity(for the tap effect and clicks), View for the alignment of texts. and certain styling. I am providing you the code snippet that will work for you , all other syntax will remain same
import {Text, View, TouchableOpacity} from 'react-native'
<View style={{flexDirection:'row'}}>
<TouchableOpacity onPress={{()=>doSomethingAndroid()}}>
<Text>Android</Text>
</TouchableOpacity>
<TouchableOpacity onPress={{()=>doSomethingiOS()}}><Text> iOS</Text>
</TouchableOpacity>
<TouchableOpacityonPress={{()=>doSomethingReactNative()}}><Text> React Native</Text>
</TouchableOpacity>
</View>
i hope this works, comment back if any issue happens
You can wrap each clickable words into 'TouchableOpacity' component, and tract the onPress event as follows
<View style={{flexDirection: 'row'}}>
<TouchableOpacity onPress={() => {
console.log('Android Clicked');
}}>
<Text>Android</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => {
console.log('iOS Clicked');
}}>
<Text>Ios</Text>
</TouchableOpacity>
</View>
Please do adjust the spacing between words.
Edit:
For dynamic string you can proceed as follows
...
handleWordClick(str, handler) {
var words = str.split(' '), // word separator goes here,
comp = [];
words.forEach((s, ind) =>{
comp.push(
<TouchableOpacity key={ind} onPress={() => handler.call(this, s)}>
<Text>{s}</Text>
</TouchableOpacity>
);
})
return comp;
}
render() {
var comp = this.handleWordClick('Android iOS React-Native', (word) => {
//handle analytics here...
console.log(word);
});
return (
<View>
...
<View style={{flexDirection: 'row'}}>
{comp}
</View>
...
</View>
)
}
I am not sure what will be your word separator as the example you have given has 'React Native' as single word. Please pay attention on this part.
Hope this will help you.

How focus the next field input in react native?

I need focus the next field input in react native, in android platform.
But the focus() function, not exists in android react native, only in IOS.
How make this ? I use react native with typescript.
The focus function works just fine.
<View style={{flexDirection: 'row'}}>
<Text style={{flex: 1}}>Enter Name: </Text>
<TextInput ref="name" onChangeText={(name) => this.setState({name})} style={{flex: 1}}
onSubmitEditing={() => this.refs.age.focus()}/>
</View>
<View style={{flexDirection: 'row'}}>
<Text style={{flex: 1}}>Enter Age: </Text>
<TextInput ref="age" keyboardType="numeric" onChangeText={(age) => this.setState({age})} style={{flex: 1}}
onSubmitEditing={() => this.refs.sport.focus()}/>
</View>
<View style={{flexDirection: 'row'}}>
<Text style={{flex: 1}}>Enter Favourite Sport: </Text>
<TextInput ref="sport" onChangeText={(sport) => this.setState({sport})} style={{flex: 1}}/>
</View>
Hope this helps. This is for android.
You have to user ref on Inputs where you want to focus on:
<Input
ref={(node) => { this.myInput = node }}
value={this.state.myInput.toString()}
onSubmitEditing={() => { this.myOtherInput.focus() }}/>
<Input
ref={(node) => { this.myOtherInput = node }}
value={this.state.myOtherInput.toString()}/>
You can see that when you submit the editing on the first input you will focus on the second one. you can use this.MY_CUSTOM_REF.focus() wherever you want.
This work for me:
<Input
blurOnSubmit={false}
returnKeyType="next"
onSubmitEditing={() => {
this.passwordInput.wrappedInstance.focus();
}}
/>
<Input
secureTextEntry
ref={(input) => {
this.passwordInput = input;
}}
/>
I insert the function in my customize component.
public focus(){
this.input.focus()
}
Have a look at this article, this might be handy react-native inputs
//Helper function
focusNextField(nextField) {
this.refs[nextField].focus();
}
<TextInput
ref='1'
style={styles.otpInputStyle}
keyboardType='numeric'
secureTextEntry
value={this.props.otp1}
maxLength={1}
onChangeText={(num) => {
this.props.otpCode1(num); //action call
if (num && num.length === 1) {
this.focusNextField('2'); //function call. '2' ref to next input ref
}
}}
/>
import React, { useRef } from 'react';
...
export default function YourFuctionalComponent() {
const input1 = useRef(null);
const imput2 = useRef(null);
const doSomething = () => {}
return(
<>
<TextInput
autoFocus
ref={input1}
onSubmitEditing={() => { imput2.current.focus(); }}
returnKeyType="next"
/>
<TextInput
ref={input2}
onSubmitEditing={() => doSomething()}
returnKeyType="done"
/>
</>
);
}
https://i.stack.imgur.com/W6dvs.gif

Categories

Resources