Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: __WEBPACK_IMPORTED_MODULE_0_react___default.a.createRef is not a function

I am new to React.js and just now i was learning the concept of ref in React. They have new createRef API in V16.3. I was trying to learn this from REACT DOC's like this -

import React from "react";

export class MyComponent extends React.Component {

constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
}

focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
}

render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
        <div>
            <input
                type="text"
                ref={this.textInput} />

            <input
                type="button"
                value="Focus the text input"
                onClick={this.focusTextInput}
            />
        </div>
    );
}

}

And I was Getting this Error -

TypeError: __WEBPACK_IMPORTED_MODULE_0_react___default.a.createRef is not a function

Here is the screenshot -enter image description here

like image 450
hardy Avatar asked Jun 01 '18 09:06

hardy


2 Answers

You do not seem to have the correct version of react installed

Do this :

npm install --save [email protected] [email protected]
like image 196
supra28 Avatar answered Oct 02 '22 06:10

supra28


If you can't upgrade your react version, you can use legacy string refs (https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs)

You set string for ref attribute:

<input
    type="text"
    ref="textInput" />

And access it like this:

this.refs.textInput.focus();

And don't forget to remove this part:

this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
like image 29
Gregor Ažbe Avatar answered Oct 02 '22 06:10

Gregor Ažbe