Search code examples
react-nativereact-native-textinput

Change TextInput editable attribute when I press a button (Not working)


I am trying to change editable with state with the click of a button, but it is not working for some reason. I have seen other people do it this way and it works. Is there another way to do this instead? or am i missing something? Thanks

`class Settings extends Component {
  constructor(props) {
   super(props);
    this.state = {
       editable: false,
       name: '',
    };

    this.handleEdit = this.handleEdit.bind(this);
    this.handleName = this.handleName.bind(this);
  }

  handleEdit() {
    this.setState({
      editable: !this.state.editable,
    });
  }

  handleName = (text) => {
    this.setState({
      name: text,
    });
  };

  render() {
    return(   
      <View style={styles.container}>
        <View style={styles.headerContainer}>
          <Text style={styles.header}>Settings</Text>
        </View>
        <View style={styles.section}>
          <View style={styles.sectionTitleContainer}>
            <Text style={styles.sectionTitle}>My Account</Text>
          </View>
          <View>
            <Text>Name:</Text>
            <TextInput
              placeholder="name"
              value={this.state.name}
              onChangeText={this.handleName}
              editable={this.state.editable}
            />
          </View>
          <View>
            <TouchableOpacity onPress={() => this.handleEdit}>
              <Text>Edit</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    );
  }
}
export default Settings;`

Solution

  • Change your

    <TouchableOpacity onPress={() => this.handleEdit}>
    

    To

    <TouchableOpacity onPress={this.handleEdit}>
    

    I believe that since you already binded 'this' to the handleEdit function you dont need to pass the () => anymore.