Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ref={...} gets now called before element exists in DOM (?) #768

Closed
cmaster11 opened this issue Jul 24, 2017 · 3 comments
Closed

ref={...} gets now called before element exists in DOM (?) #768

cmaster11 opened this issue Jul 24, 2017 · 3 comments

Comments

@cmaster11
Copy link

cmaster11 commented Jul 24, 2017

After updating from ~7 to latest (8.2.1), I noticed this curious behavior:

When using ref={(el) => ...} over a div element (my case), with the previous version I was able to use el.parentNode to traverse up the DOM tree and get refs to parents and so on.

With new version, el.parentNode is undefined, which makes me think the element gets generated but not yet inserted in the DOM tree? I can't figure out if this is a bug or if it's just a side-effect related to an improvement introduced in the last releases.

@cmaster11 cmaster11 changed the title onRef gets now called before element exists in DOM (?) ref gets now called before element exists in DOM (?) Jul 24, 2017
@cmaster11 cmaster11 changed the title ref gets now called before element exists in DOM (?) ref={...} gets now called before element exists in DOM (?) Jul 24, 2017
@developit
Copy link
Member

It was a change in 8, yes. I would recommend avoiding tree traversal from within a ref, it's not what refs are designed for. They're purpose is to allow you to store a reference and nothing more. If you want to traverse the tree, it's best to do so from a lifecycle event:

class Foo extends Component {
  fooRef = c => {
    this.foo = c;
  };

  componentDidMount() {
    // use the ref
    let parentWidth = this.foo.parentNode.offsetWidth;
  }

  render() {
    return <div ref={this.fooRef} />
  }
}

@cmaster11
Copy link
Author

Thank you for the reply, I guess it's time to change some code here then! ;)

@marvinhagemeister
Copy link
Member

We've fixed this for Preact X for which the code just landed in master via #1302 . An alpha release should be available soon 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants