react-bulma icon indicating copy to clipboard operation
react-bulma copied to clipboard

Suggested approach for focussing inputs after render

Open samlown opened this issue 6 years ago • 4 comments

Is there a suggested approach for focussing input fields when a component is rendered? The autoFocus parameter works on a page refresh, but not when replacing the current contents.

The following approach does not work as the ref is associated with the Input class instance as opposed to the rendered input tag, and the focus() call is not forwarded:

componentDidMount() {
  this.inputField.focus();
}

render() {
  return (
     <div>
        <Input ref={ (input) => { this.inputField = input } } name="foo" /> 
     </div>
  )
}

I'm quite new to React, so maybe I'm missing something.

Thanks.

samlown avatar Mar 13 '18 14:03 samlown

You should use findDomNode()

kulakowka avatar Mar 13 '18 14:03 kulakowka

My understanding is that the use of this method is not recommended. It also doesn't appear to work in preact. Perhaps for these cases it will be easier just to provide the input box manually.

samlown avatar Mar 13 '18 14:03 samlown

I think this is a preact problem, not this library. Why you do not want to use findDomNode?

We could introduce a new props "inputRef", but this does not seem to me to be the right decision.

kulakowka avatar Mar 13 '18 15:03 kulakowka

It looks like findDomNode is supported in the preact-compat module, but I'd honestly prefer to keep the code as lean as possible.

Given that focus() is an important function for Input boxes, perhaps it's worth adding a wrapper method to the Input component? That way the regular and recommended ref can be used without issue.

samlown avatar Mar 16 '18 17:03 samlown