Nhawdge / nhawdge-netlify

BSD Zero Clause License
0 stars 0 forks source link

Blog idea - React Refs #1

Open Nhawdge opened 3 years ago

Nhawdge commented 3 years ago

The callback ref thing is fairly elegant. In your constructor you make a function that captures a reference to your DOM object when it renders:

    this.modelElem = null;
    this.setModelRef = element => {  
      this.modelElem = element;    
    };    

Then when you render you feed it the set method:

        <model-viewer
          ref={this.setModelRef}>
and then you can hook events and use other methods on your component when it mounts
  componentDidMount() {
    this.modelElem.addEventListener('load', e => {
      this.modelElem.className += " model-loaded";
      if (typeof this.props.onModelLoad === "function") {
        this.props.onModelLoad(e);
      }
    })
    this.modelElem.addEventListener('progress', e => {
      this.setState({progress: e.detail.totalProgress});
    })    
  }
Nhawdge commented 3 years ago

https://reactjs.org/docs/refs-and-the-dom.html#callback-refs