Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.createRef() causing error 'expected ref to be function or string'

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>
        );
    }
}
like image 732
aditi Avatar asked May 11 '18 19:05

aditi


People also ask

Can createRef be used in functional component?

The refs created using the createRef can be referenced throughout the component. It is used in functional components.

How initialize createRef in React?

Here is the code snippet: const MyComponent = (props) => { const formInput = React. createRef(); const inputSelection = () => { const input = formInput. current; if (input.

What is createRef ()?

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.

Is createRef a hook?

It is not the same as simply calling createRef , as createRef isn't a hook and doesn't persist any state between calls.


1 Answers

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

  • make sure you got the latest versions of both react and react-dom (16.3.2) declared in package.json
  • then removed node_modules and install it again
like image 93
Tomasz Mularczyk Avatar answered Oct 23 '22 02:10

Tomasz Mularczyk