I upgraded my React to 16.3.2 and used React.createRef()
as seen here: https://reactjs.org/docs/react-api.html#reactcreateref
But when I am getting the following error:
Uncaught Error: Expected ref to be a function or a string.
When I look at what the function React.createRef() actually returns, I see this:
{ current: null }
What is going wrong here? Has the implementation changed?
I am using react-router-dom for routing, and my component is a class
component.
EDIT: this is my code:
export class MyComponent extends Component {
constructor(props) {
super(props);
this.cardRef = React.createRef();
}
render() {
return (
<div>
...
<Card ref={this.cardRef}>
...
</Card>
</div>
);
}
}
The refs created using the createRef can be referenced throughout the component. It is used in functional components.
Here is the code snippet: const MyComponent = (props) => { const formInput = React. createRef(); const inputSelection = () => { const input = formInput. current; if (input.
Refs are created using React.createRef() and attached to React elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component. class MyComponent extends React.
It is not the same as simply calling createRef , as createRef isn't a hook and doesn't persist any state between calls.
To address this:
What is going wrong here? Has the implementation changed?
Nope. It just returns an Object with a property current
being set to null. No magic here. You just initiate property in a component with such object and then you pass a reference of this object to the component. React then at some point reassigns current
.
this.component = React.createRef() // this.component = { current: null }
// we pass a reference to object above and react will mutate current property at some point
<div ref={this.component} />
The error message seems to suggest you are still using an older version of react. What I would suggest is to
react
and react-dom
(16.3.2) declared in package.json 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