Source:  Twitter logo

I am trying to clear the defaultValue of an input on focus and having trouble doing it either inline or in an external function. Thoughts on the best way to do this? If I use value instead of defaultValue it's the same issue.

const SomeComponent = (inputValue) => {

<input type="text"
  defaultValue={inputValue}
  onFocus = // clear input defaultValue 
  onBlur={() => dosomething()}/>
}

export default SomeComponent

If you want to use React's ref, you can do something like this:

const SomeComponent = (inputValue) => (

  <input type="text"
    defaultValue={inputValue}
    ref={input => this.inputField = input}
    onFocus = {() => this.inputField.value = ""} 
    onBlur={() => dosomething()}/>
)

export default SomeComponent
3 users liked answer #0dislike answer #03
Nick Wyman profile pic
Nick Wyman

The resetting function

const resetInput = (e) => {
  e.target.value = "";
}

The input HTML

<input type="text"
  defaultValue={inputValue}
  onFocus={(e) => resetInput(e)}
  onBlur={() => dosomething()}/>
}

Or one onFocus one-liner

<input type="text"
  defaultValue={inputValue}
  onFocus={(e) => e.target.value = ""}
  onBlur={() => dosomething()}/>
}
2 users liked answer #1dislike answer #12
Kenny Ye profile pic
Kenny Ye

Would this work? onFocus={e => e.target.value == inputValue ? e.target.value = '' : return null}

1 users liked answer #2dislike answer #21
inostia profile pic
inostia

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).