Clearing a Textinput using a TouchableOpacity without dismissing the keyboard? - react-native

i want to build a super simple chat.
To do that a got an TextInput and a TouchableOpacity to send the message and
clear the Textinput.
Problem: When i send the message the Textinput is cleared BUT when start writing again the old text is copied in the Textinput again (+ the new character).
However if the keyboard is dismissed after sending and clearing everything works
perfectly fine.
Is there any way to clear the TextInput completly with a TouchableOpacity?
Below is the code and a few tries by myself but none of them worked.
Thanks in advance,
Maffinius
<View style={{flexDirection: 'row'}}>
<TextInput
placeholder="Schreibe eine Nachricht"
onChangeText={(text) => this.setState({newMsg : text})}
style={{width: 300}}
ref={'ref1'}
/>
<TouchableOpacity
onPress={this.sendMessage}
>
<Text> --> </Text>
</TouchableOpacity>
</View>
sendMessage = () => {
this.state.MsgData.push({msg: this.state.newMsg, id: this.props.global.userId, timestamp: 8888});
this.refs['ref1'].clear();
this.setState({newMsg: ""});
//this.refs['ref1'].setNativeProps({text: ''})
//Keyboard.dismiss();
}
List item

Use defaultValue prop for setting the value of the state (https://facebook.github.io/react-native/docs/textinput.html#defaultvalue)
<TextInput
placeholder="Schreibe eine Nachricht"
onChangeText={(text) => this.setState({newMsg : text})}
style={{width: 300}}
ref={(input) => this.ref1 = input}
defaultValue={this.state.newMsg}
/>
See this example for full implementation: https://snack.expo.io/SkuH8hKPb

Related

Trigger event on component from another component

I am unsure how to trigger an event in my TouchableOpacity component that will target the TextInput component. I'd just like to be able to allow the user to type in a multiline area and click a button when they are finished, so that they are able to save their text (similar to how the iOS Notes app functions).
<View>
<View>
<Text>Notes</Text>
{typing &&
<TouchableOpacity
onPress={() => {
//blur() the textinput here
}}
>
<Text>Done</Text>
</TouchableOpacity>
}
</View>
<View>
<TextInput
multiline={true}
textAlignVertical='top'
value={text}
onChangeText={(text) => {
}}
onFocus={setTyping(true)}
/>
</View>
</View>
If you only need to access the text inside the same file, store your text in state in your component.
const [text, setText] = useState('');
...
<TouchableOpacity
// not sure what you want to do with the text here, but it'll be available in the `text` variable
onPress={() => saveNote(text)}
...
<TextInput
onChangeText={newText => setText(newText)
// or more simply
onChangeText={setText}
...
/>
The text input will automatically blur when you touch the Touchable.
If you need the text available in other files, have a look into React Context or look up state management libraries for React Native.

How to add red asterisk in react native TextInput placeholder?

Inside TextInput, I want to have a red asterisk after placeholder text which is grey in color.
<TextInput
keyboardType="numeric"
placeholder={t('Enter OTP')}
placeholderTextColor="#C4C4C4"
value={inputOTP}
onChangeText={text => setInputOTP(text)}
style={styles.textInput}
/>
I want a red asterisk next to P in EnterOTP.
Is absolute position the only way to do it?
There is no direct method to do this.What I did is add text with asterix in front of the TextInput and show hide conditionally when there is value in TextInput or not,
const [title, setTitle] = useState();
const {
control,
handleSubmit,
formState: {errors},
} = useForm({});
<View style={{flexDirection: 'row',}}>
<Controller
control={control}
rules={{
required: true,
}}
render={({field: {onChange, onBlur, value}}) => (
<TextInput
autoFocus
onChangeText={(val) => {
onChange(val);
setTitle(val);
}}
value={value}
onBlur={onBlur}
placeholder={'Type activity name here'} >
</TextInput>
)}
name="activityName"
/>
{title ? <Text></Text> : <Text style={{color: 'red',fontSize: 17,height: 13,}}>*</Text>}
</View>
The Controller here comes from react-hook-forms which is not related to this question.You can use TextInput without Controller also.
TextInput naturally does not support the behaviour you mentioned (Placeholder with multiple colors) but with a small trick you will be able to achieve what you want!
put a text with red asterisk
<Text style={{ color: 'red' }}>* * *</Text>
try to give it a position which will sit beside your OTP text in placeholder . in TextInput component we have onFocus props which will be triggered when you enter the text input and want to type in!
so here you can make the mentioned text conditional! when it is not focused and there is no character inside you will show the red asterisk text otherwise you won't show it.

React Native TextInput returnKeyType not working

I have a number of TextInput in my react-native application and I want that if user clicks on next key, the next input must be focused. I am trying to do this with returnKeyType prop passed to all the TextInput. However this doesn't work as intended ,i.e. next input is not focused. And my code for same looks like
<TextInput
ref={firstInputForDaysInterestTextInputRef}
value={closingCosts.firstInputForDaysInterest}
onChangeText={value =>
onStateChange('firstInputForDaysInterest', value)
}
onEndEditing={event =>
onEndEditing(
'firstInputForDaysInterest',
event.nativeEvent.text,
)
}
placeholderTextColor={colors.placeholderColor}
placeholder={constants.common.zeroPlaceholder}
autoCapitalize="none"
returnKeyType="next"
onFocus={() => onFocus(elementName)}
keyboardType="decimal-pad"
style={[
styles.textInput,
styles.textInputWidth,
styles.textInputMargin,
]}
/>
The workaround that I thought was passing ref and then focusing the next input onEndEditing, but if I does this the textinput will not be closed when I tap outside the textInput. So how can I make my text input to focus on next one?
You can use onSubmitEditing prop to focus the next input for example:
const firstInputForDaysInterestTextInputRef = React.useRef()
const secondInputForDaysInterestTextInputRef = React.useRef()
return (
<View style={styles.container}>
<TextInput
ref={firstInputForDaysInterestTextInputRef}
placeholderTextColor={'gray'}
placeholder={'first'}
autoCapitalize="none"
returnKeyType="next"
keyboardType="decimal-pad"
onSubmitEditing={()=>secondInputForDaysInterestTextInputRef.current?.focus()}
style={[
styles.textInput,
styles.textInputWidth,
styles.textInputMargin,
]}
/>
<TextInput
ref={secondInputForDaysInterestTextInputRef}
placeholderTextColor={'gray'}
placeholder={'second'}
autoCapitalize="none"
returnKeyType="next"
onFocus={() => alert('I am focused !')}
keyboardType="decimal-pad"
style={[
styles.textInput,
styles.textInputWidth,
styles.textInputMargin,
]}
/>
</View>
);
Example on Snack
If you want to hide the textinput (hide keyboard) when pressing somewhere else in the app, wrap it it like this for example:
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.container}>
<TextInput />
</View>
</TouchableWithoutFeedback>
Don't forget to import TouchableWithoutFeedback and Keyboard from 'react-native'

Call onBlur on tap of outside the textInput component

render(){
return(
<View style={{ flex:1 }}>
<TextInput style={{ backgroundColor:'red'}} onFocus={() => alert('Focued')}
onBlur={() => alert('Blurred') }
/>
</View>
)
}
In the above code snippet when I click on textinput the focus operation is working, but when I click outside the textinput component onBlur is not triggered.
I don't want to enclose the component in scrollview
could any one help me out on this.

How to disable keyboard in react native

I created a screen keyboard component that I want to disable the platform's keyboard, how I can disable it?
<TextInput
secureTextEntry
ref="Pin"
selectionColor="#656565"
keyboardType="numeric"
activeColor="#656565"
inactiveColor="#fff"
autoFocus={false}
ignoreCase
codeLength={4}
inputPosition="center"
size={50}
onFulfill={isValid => this}
codeInputStyle={{ borderWidth: 1.5 }}
/>
Just write showSoftInputOnFocus={false} in <TextInput> like this:
<TextInput showSoftInputOnFocus={false} />
I had issues also. No other solutions was working for me. This will display text input field and it will be clickable but not editable.
<TouchableOpacity onPress={this.openPinKeyboard}>
<View pointerEvents="none">
<Input editable={false} value="1234" />
</View>
</TouchableOpacity>
I think you need to add something like:
<TextInput showSoftInputOnFocus={false} keyboardType="numeric" />
setting keyboardType to null worked for me
EDIT:
this only worked in the simulator, running it on an actual device the native keyboard still appeared.
wrapping the <TextInput /> in a <TouchableWithoutFeedback> element in the example below worked.
<TouchableWithoutFeedback onPress={Keyboard.dismiss} >
<TextInput />
</TouchableWithoutFeedback>
You may try to set keyboardType to none, if it doesn't work another alternative is to set the editable prop to false.
Potential answers can be found here : https://github.com/facebook/react-native/issues/14045
<TextInput showSoftInputOnFocus={false}/>
This work for me, sometime I need onFocus action to navigate new screen, and don't need keyboard open animation. Prop Editable will disable textfield, can not pressable
try this solution i hope this will work for android and ios both...
// Step 1: Get Keyboard, TouchableWithoutFeedback from ‘react-native’;
import { View, TextInput, StyleSheet, Keyboard, TouchableWithoutFeedback } from 'react-native';
// Step 2: Create an arrow function to write dismiss keyboard code
const DismissKeyboard = ({ children }) => (
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
{children}
</TouchableWithoutFeedback>
);
// Step 3: Wrap all TextInput inside <DismissKeyboard> </DismissKeyboard>
//Example
<DismissKeyboard>
<View style={styles.container}>
<TextInput style={styles.input} placeholder="email" />
<TextInput style={styles.input} placeholder="password" />
</View>
</DismissKeyboard>
The easiest solution is to use the onFocus prop on TextInput.
Import Keyboard from ‘react-native’
import {Keyboard, TextInput} from
'react-native'
Then pass Keyboard.dismiss() to TextInput onFocus prop, to stop the keyboard from popping up when focused.
<TextInput onFocus = {()=> Keyboard.dismiss()} .../>
Now test the input field by pressing it to see if the keyboard will pop up
just put this under text input tag this worked for me in react-native
<TextInput
//this line
editable={false}
/>
you can do it by pointerEvents="none"
<View pointerEvents="none">
<TextInput
focusable={false}
style={{color: '#00000000'}}
onChangeText={setEmail}
/>
</View>