How to use React refs to focus a Redux Form field?

10,343

Please try setting ref using callback function:

ref={(input) => { this.title = input; }}

and then use this to get underlying DOM node:

ReactDOM.findDOMNode(this.title).focus();

of if DOM input element is wrapped in another element:

ReactDOM.findDOMNode(this.title).getElementsByTagName("input")[0].focus()

According to React docs using refs with a string have some issues. Please check docs for more details.

Share:
10,343

Related videos on Youtube

Trey Granderson
Author by

Trey Granderson

Digital Creator on the Front End. Hungrily consuming knowledge.

Updated on June 15, 2022

Comments

  • Trey Granderson
    Trey Granderson almost 2 years

    I am trying to use React refs to focus a Redux-Form Field when it mounts.

    When I try this.refs.title.getRenderedComponent().focus() in componentDidMount, an error is thrown saying:

    edit_fund.js:77 Uncaught TypeError: Cannot read property 'getRenderedComponent' of undefined

    When I console.log this.refs, it is mostly an empty object and sometimes identifies 'title' as being a ref, but it is not dependable.

    Am I using refs incorrectly? My code is below for reference.

    componentDidMount = () => {
      this.refs.title
      .getRenderedComponent()
      .focus();
    }
    

    ...

     <Field
        id="title"
        name="title"
        component={FormInput}
        type="text"
        ref="title" withRef
     />
    
    • Freez
      Freez over 7 years
      This is weird, your code looks fine, please show the entire component code
    • Trey Granderson
      Trey Granderson about 7 years
      No, never solved it unfortunately.
  • Madhur
    Madhur almost 5 years
    I have tried your solution It works but with that i am not able to next textbox it stuck on single input box. please help me.
  • Madhur
    Madhur almost 5 years
    const node = findDOMNode(refs); if (node) { node.focus() }
  • Matthew Francis
    Matthew Francis over 3 years
    What if the redux form is defined in a functional component rather than a class?