2

I'm trying to use refs is ReactJs, to focus the textbox from a button click.

But I get the following error message:-

bundle.js:114 Uncaught TypeError: Cannot read property 'focus' of undefined

Source Code

class FocusText extends Component{

        handleClick(){
            this.refs.myTextInput.focus();
        }

        render(){
            return(
                <div>
                    <input type="text" ref="myTextInput"/>
                    <input type="button"
                           value="Focus the text input"
                           onClick={this.handleClick.bind(this)}/>
                </div>
            );
        }
    }

    React.render(<FocusText/>, document.getElementById('root'));
Derek
  • 8,300
  • 12
  • 56
  • 88

3 Answers3

3

String refs are deprecated, and according to the docs...

We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases.

You should use the callback ref instead.

Assign the ref to a property on the instance:

<input type="text" ref={(input) => { this.myTextInput= input; }} />

Use the ref:

handleClick(){
    this.myTextInput.focus(); // note that refs is no longer necessary 
}
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
2

Try using a callback:

class FocusText extends React.Component{

        handleClick(){
            console.log(this.focus)
        }

        render(){
            return(
                <div>
                    <input type="text" ref={ focus => this.focus = focus }/>
                    <input type="button"
                           value="Focus the text input"
                           onClick={this.handleClick.bind(this)}/>
                </div>
            );
        }
    }

    React.render(<FocusText/>, document.getElementById('app'));

From React documentation:

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

https://facebook.github.io/react/docs/refs-and-the-dom.html

Avraam Mavridis
  • 8,698
  • 19
  • 79
  • 133
  • It was failing because i was using React.render rather than using the ReactDOM.render from 'react-dom'. :-( – Derek Jul 17 '17 at 08:44
2

Like the others have said, string refs have been deprecated.

However it still works right now with the string ref, but in the last line I would use ReactDOM

ReactDOM.render(<FocusText />, document.getElementById("root"));

In your code you aren't using ReactDOM. Is there are reason for that?

See the CodePen

Dan Kreiger
  • 5,358
  • 2
  • 23
  • 27