Adam McGurk
Adam McGurk

Reputation: 476

Changing state of react native textinput on focus

I'm trying to make my placeholder text go away onFocus in a React Native TextInput component. The function is being called and the state is changing, but the placeholder remains. Here is the component code:

import React from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';

export class GeneralInput extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            placeholder: this.props.placeholder
        };
     }
    whenInputIsFocused() {
        console.log('Before changing the state');
        this.state.placeholder = "";
        console.log('After changing the state');
        console.log(this.state);
    }
  render() {
    console.log(this.state);
    return(
        <View style={styles.outerContainer}>
            <Text style={styles.labelText}>{this.props.labelText}</Text>
            <TextInput autoCapitalize='none' secureTextEntry={this.props.secureTextEntry} onFocus={this.whenInputIsFocused.bind(this)} underlineColorAndroid="transparent" keyboardType={this.props.type} returnKeyType={this.props.returnKeyType} placeholder={this.state.placeholder} placeholderTextColor='rgba(255, 255, 255, 0.3)' style={styles.inputStyles} />
        </View>
    );
  }
}

Here is the console log output:

[09:39:18] Before changing the state
[09:39:18] After changing the state
[09:39:18] Object {
[09:39:18]   "placeholder": "",
[09:39:18] }

Why does my TextInput placeholder not disappear, even though the function is being called and the state is updated?

Upvotes: 0

Views: 2487

Answers (1)

schogges
schogges

Reputation: 459

This is a normal behaviour. The placeholder will disappear if you enter a text, but you are missing two important properties.

<TextInput>
  onChangeText={(text) => this.setState({text})}
  value={this.state.text}
</TextInput>

value sets the text (not placeholder) and keeps it inside the TextInput. onChangeText changes the text by setting the State. On start this.state.text should contain empty string ""

edit: If you want to make placeholder disappear, you need to set it by

this.setState({placeholder: ""});

Using this.setState() will force a rerender.

Upvotes: 2

Related Questions