3

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
Kirk Ross
  • 6,413
  • 13
  • 61
  • 104

3 Answers3

3

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
Nick Wyman
  • 1,150
  • 11
  • 18
  • This shouldn't work, stateless functional components don't have `ref`s because these are just regular functions (and `this` in your example wouldn't refer to the component) – pawel Mar 09 '17 at 22:42
  • I'll be the first to admit, I'm no expert in React, so it may be doing something it shouldn't be. But if you pass in a function to the ref, even in stateless components like this it will provide you an object you can reference later. I wouldn't recommend this approach if the functions had more complexity. But if it the functionality is just focusing on the input, it seems like it is working as expected. – Nick Wyman Mar 10 '17 at 14:04
  • paste your code to babel.io/repl and you'll see that `this` gets thranspiled to `undefined`. Or try to run it and it will throw "TypeError: Cannot set property 'inputField' of undefined" – pawel Mar 10 '17 at 14:12
  • Thanks pawel, it looks like you're right. For some reason my babel/webpack setup is transpiling the component and including an instance of "this" for it to use, letting the above code work. – Nick Wyman Mar 10 '17 at 15:11
2

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()}/>
}
Kenny Ye
  • 587
  • 1
  • 5
  • 12
1

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

inostia
  • 7,777
  • 3
  • 30
  • 33