Areza
Areza

Reputation: 721

how can I clear Native-base Input text?

I try this

  <Input placeholder="search...."
         ref={(ref) => { this.SearchInput = ref; }}
         />
  <Button transparent onPress={this.clear}>
      <Ionicons name="ios-close" />
  </Button>

and function:

  clear = () => {
    this.SearchInput.clear();
  }

I get this error:

this.SearchInput.clear() is not a function

Upvotes: 1

Views: 4324

Answers (3)

user8453321
user8453321

Reputation: 344

i totally agree with Muhammad Hanzala as it worked for me on this but there is a little exception which is really important which i had to do to make it work be sure to add the reference of the text input to your constructor like this:

constructor()
  {
    ...
   this.SearchInput = React.createRef();
  }

A full example will look like this in your input element...

<InputgetRef={(ref) => this.SearchInput = ref}/>

in your constructor :

constructor()
  {
    ...
   this.SearchInput = React.createRef();
  }

and finally you can call:

this.SearchInput._root.clear(); 

and dont forget to clear your state..

Upvotes: 0

Komang Sidhi Artha
Komang Sidhi Artha

Reputation: 321

I use value and state to achieve this functionality

here is the example:

<Input
  value={ this.state.value }
  onChangeText={ this.onTextChange }
/>
<Button onPress={this.clear}>
  <Ionicons name="ios-close" />
</Button>

declare default value's value on constructor

this.state = {
  value: ''
}

listen to onTextChange as follows, this make sure that the value on Input stay the same as we inserting, not blank forever:

onTextChange = (value) => {
  this.setState({ value })
}

finally, on clear function

clear = () => {
  this.setState({ value: '' })
}

just set back value to empty

Upvotes: 3

Muhammad Hanzala
Muhammad Hanzala

Reputation: 105

This is the running code, change ref to getRef and use this.SearchInput._root.clear(); instead of this.SearchInput.clear();

  clear = () => {
    this.SearchInput._root.clear();
  }
  render() {
    return (
      <Container>
        <Header />
        <Content>
          <Item floatingLabel>
            <Input placeholder="search...."
              getRef={(ref) => this.SearchInput = ref}
            />
          </Item>
          <Button onPress={this.clear}>
            <Ionicons name="ios-close" />
          </Button>
        </Content>
      </Container>
    );
  }

Upvotes: 5

Related Questions