Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.refs.something returns "undefined"

I have an element with a ref that is defined and ends up getting rendered into the page :

    <div ref="russian" ...>        ...     </div> 

I want to access the DOM element properties like offset... or something. However, I keep getting undefined and I haven't the faintest idea why. After some searching it's clear that refs are only applicable to one file but I'm not using this anywhere besides this one page. I'm saying this to log it:

console.log('REFS', this.refs.russian);

What could be causing this?

like image 790
John Doe Avatar asked Feb 05 '16 17:02

John Doe


People also ask

Why is my ref undefined?

If we try to access the current property of the ref directly in the component, we would get undefined back because the ref hasn't been set up and the div element has not been rendered. You can also access the current property of the ref in an event handler function. Copied!

Why is ref undefined Vue?

It is because the input property itself is undefined, so we can't get access to the value property. That is because of the previous error happens during component rendering. So the computed value will be undefined as well.

How do I access Vue refs?

Accessing the Refs Note that you can only access the ref after the component is mounted. If you try to access $refs. input in a template expression, it will be null on the first render. This is because the element doesn't exist until after the first render!

What is ref in Vuejs?

Refs are Vue. js instance properties that are used to register or indicate a reference to HTML elements or child elements in the template of your application. If a ref attribute is added to an HTML element in your Vue template, you'll then be able to reference that element or even a child element in your Vue instance.


1 Answers

Check that you are not accessing ref before the child component has been mounted. E.g. it doesn't work in componentWillMount. A different pattern which auto invokes ref related callback after the element has been mounted is this-

<div ref={(elem)=>(console.log(elem))}/> 

You can use this notation to get mounted elements in deep nesting as well -

<div ref={this.props.onMounted}/> 
like image 185
hazardous Avatar answered Oct 05 '22 20:10

hazardous