Cannot empty a TextInput while in focus - react-native

I have the following issue with a TextInput
User types: Hello
Input field shows Hello
I clear the text input without losing focus
Input field shows ""
User types: A
Input field shows HelloA
If the user removes the focus from the TextInput and focuses back on it before typing again, the behavior goes as expected and the new text contains only the input from after the clearing
How can I properly clear the TextInput without the need to go off focus?
Here is the minimum code required to trigger the issue:
export default class MyInput extends Component {
clearInput() {
this.textInput.clear();
}
render() {
return (
<View>
<Button title="clear" onPress={this.clearInput.bind(this)} />
<TextInput
ref={component => (this.textInput = component)}
/>
</View>
);
}
}

Related

Can't get TextInput value in react native

Hi friends I hope you are doing very well ^^
I am struggling to get a TextInput value when a user enters it in a simple basic form I've created, here is the field :
<TextInput placeholder='latitude' name='lat'/>
<Button style={styles.signIn}
title="Show my entered text"
onPress={() => {
alert(this.state.lat)}}
/>
I tried so many methods to get the value of this field but unfortunately none works.. I am new to react native so I really don't know how can this be done properly (is there any variable I need to define) because in javascript I used to get it only by the GetElementById quite simple right XD
I tried creating a variable exactly bellow the imports like this :
value={this.state.lat}
So I can get the above textInput actual value entered by the user but it isn't working at all and my alert function is not returning anything (I actually don't know if alert() is a react native integrated function or I need to define it from scratch :/), please help I am really lost I tried many solutions on the web but nothing resolves my problem. Thanks in advance
Try this sample code
class Example extends React.Component {
state = { lat: "" };
render() {
return (
<View>
<TextInput
placeholder="latitude"
name="lat"
value={this.state.lat}
onChangeText={(text) => this.setState({ lat: text })}
/>
<Button
style={styles.signIn}
title="Show my entered text"
onPress={() => {
alert(this.state.lat);
}}
/>
</View>
);
}
}

How to stop TextInput losing focus onChangeText?

I want to change the state of a parent component from a child's TextInput.
The problem is every time it changes the parent state the component re-renders, the TextInput is blurred and the keyboard disappears.
I tried keeping all the logic in the some component and changing the parent state without passing props. Now I've tried extracting the InputText container and putting it into a new file, changing the parents' state and receiving the value through the props, that's not working either.
Here is the text field component:
export default (ProfileTextInput = ({
placeholder,
label,
handleChange,
name,
value
}) => {
return (
<View style={styles.inputComponent}>
<Text style={styles.labelText}>{label.toUpperCase()}</Text>
<TextInput
key={Math.random()}
placeholder={placeholder || ""}
value={value}
onChangeText={val => handleChange(val, name)}
/>
</View>
);
});
and this is how it's being used:
const [newUserData, setNewUserData] = useState({ ...userData });
const changeHandler = (value, name) => {
setNewUserData({ ...newUserData, [name]: value });
};
return(
<ProfileTextInput
label="Username"
defaultValue={newUserData.username}
name="username"
value={newUserData.username}
handleChange={changeHandler}
/>
)
I expected it to continue letting me type like a normal TextInput, but it's only typing one letter and losing focus.
Try removing the defaultValue props from your components.
defaultValue is just the initial value passed to an uncontrolled component. Since you're setting the input value with a change handler, that makes your input a controlled component, and so you should just set the value explicitly.
Read these articles for more details on the differences between these cases:
React forms and controlled components
Uncontrolled components

How to set value in textInput in react native

I have one text input in which i'm gonna typing some name while user typing the name get translated and back to set in text Input field how can i do this
<TextInput
style={{color:'black',width:width-60, borderColor: 'black'}}
underlineColorAndroid='black'
placeholderTextColor="black"
onChangeText={ (textValue) => this.setState({
input: textValue}) }
/>
// TRANSLATED TEXT
<PowerTranslator
text={this.state.input} />
TextInput have prop named "value".
For setting data to text input, you should set "value" to state value.
<TextInput
value={this.props.input}
/>
https://facebook.github.io/react-native/docs/textinput.html#value
In your code, power translator view component only for displaying text.
If you look at this component page, you should use it as service for getting translated text.
Translation.get('Engineering physics or engineering science').then(translated => {
//Do something with the translated text });

react native component button not enabling

import React from 'react';
import {
View,
Text,
Button,
TextInput,
StyleSheet
} from 'react-native';
const username = null;
const SetupForm = ({onSubmit}) => {
this.handleUsernameInput = (text) => {
username = text;
}
this.handleSetupSubmit = (event) => {
onSubmit(event, username);
}
this.handleSkipSubmit = (event) => {
onSubmit(event, false);
}
return (
<View>
<Text>Enter username:</Text>
<TextInput
placeholder="Username"
maxLength={20}
onSubmitEditing={this.handleSetupSubmit}
onChangeText={this.handleUsernameInput}
style={{ marginLeft: 20, marginRight: 20 }}
/>
<View>
<Button
title="Select"
onPress={this.handleSetupSubmit}
color="#34A853"
disabled={username === null}
/>
<Button
title="Maybe Later"
onPress={this.handleSkipSubmit}
color="red"
/>
</View>
</View>
);
}
export default SetupForm;
I have an issue with this Setup Form. it features a username text box I am setting to the value the user enters. onChangeText={this.handleUsernameInput}
for the select button I have set disabled when username === null however this never becomes false when entering text into the text box.
the text box is set to set the username when typing and I can see in the console its working correctly when I press the submit via the keyboard button with the redux action
{type: "SETUP.REQUEST", username: "aaaaaaa"}
is there something I am doing wrong here that the button is not becoming enabled when the text is getting set by the this.handleUsernameInput method?
example gif:
http://i.imgur.com/OuMkxHA.gifv
I have to click the skip button after typing in a username to make the button enable (go green), I want this to enable whilst typing
Like mentioned in the Garrett's comment the component doesn't re-render because there's no prop or state change when you change the text input. You should change the functional component to a ES6 class and save the username into the state. There's an simple example of this in the TextInput's documention
I'm not sure about your skill level but React's documentation about state and lifecycle is a good read if you are new to React https://facebook.github.io/react/docs/state-and-lifecycle.html

setState() adds a Proxy object to property instead of string value in react native

This is a very weird problem and I'm sure I'm overlooking something very simple.
When I load a new component AddNewCategory, I initially set a an empty string to a text property on this.state. Logging on console shows the text value as empty too.
I update this value using onChange of Button component. I know that the text property is so far updating as expected because the value of the input field changes accordingly.
<Button onChange={text=>this.setState({})}>
But when I try to retrieve the value of text property, I see that instead of a string, the text is now assigned a Proxy object.
I'm only trying to get the value of the input field so I can pass the value on to an action creator.
Here's the entire code,
import React from 'react';
import { View, Text, TextInput, Button} from 'react-native';
class AddNewCategory extends React.Component {
constructor(props) {
super(props)
this.state={
text: ''
};
console.log('after initialising constructor');
console.log(this.state);
this.onContinueButtonPress = this.onContinueButtonPress.bind(this);
}
onContinueButtonPress() {
console.log('after onContinueButtonPress');
console.log(this.state);
this.props.addNewCategory('Random Value');
}
render(){
return(
<View>
<Text>Name your new task list</Text>
<TextInput
placeholder="Things to do today.."
value={this.state.text}
onChange={(text)=>this.setState({text: text})}
/>
<Button
title={'Continue'}
onPress={this.onContinueButtonPress}
/>
</View>
);
}
};
export default AddNewCategory;
I have no idea why you are giving an onChange prop to a Button component.
Anyway, for a TextInput, you should give the onChangeText property.
<TextInput onChangeText={text => this.setState({ text })}
Other properties have been omitted.
Using just onChange is like handling the usual onChange event when doing web development, where the first parameter to the callback method only gives the event; to get the actual input value you have to say event.target.value.
onChange={(event) => console.log(event.target.value)}