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 -
You do not seem to have the correct version of react installed
Do this :
npm install --save [email protected] [email protected]
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With