0
votes

So I am trying to use the ref callback pattern explained here: https://facebook.github.io/react/docs/refs-and-the-dom.html, but continue to get undefined in the Parent's componentDidMount method

const Child = ({ createFormHeight, getChildRef }) => (
  <CreateForm createFormHeight={createFormHeight}>
    // getting reference from here
    <div ref={getChildRef}>
      // form markup here
    </div>
  </CreateForm>
);

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      createFormHeight: '',
    }
  }

  componentDidMount() {
    const createFormHeight = this.formWrapper.offsetHeight; // returns 
error that this.formWrapper is undefined
    this.setFormHeight(createFormHeight);
  }

  getChildRef = (el) => {
    // if I console.log(el) it returns the div here
    this.formWrapper = el;
  }

  setFormHeight = (height) => {
    this.setState(() => ({ createFormHeight: height }));
  };

  render() {
    const { createIsOpen, createFormHeight } = this.state;
    return (
      <CreateMember createFormHeight={createFormHeight} getChildRef=
{this.getChildRef} />
    );
  }
}
1
add one console.log to componentDidMount and one to getChildRef, see which one logs first.bennygenel

1 Answers

0
votes

I guess the problem is you didn't mount your getChildRef to the context. Try add this.getChildRef = tihs.getChildRef.bind(this) to the constructor of Parent.