Goran Tesic
Goran Tesic

Reputation: 739

How do I pass React.createRef() to a child component?

In my sidebar I have a list of radio buttons that should each select a component located in the main area of my app. I would like to set it so the component scrolls into view when I click the radio button that selects it, and as far as I can figure, I need to reference the component in order to scroll it into view, but I'm having trouble with this because I can't figure out how to properly pass a reference from child to parent component.

The parent component is a class component and in its constructor I set createRef() like this:

constructor(props) {
  super(props);
  this.myRef = React.createRef();
}

I then created a function that should be passed to child component and return ref:

getElem(ref) {
  this.myRef = ref;
}

Now, inside the render of the parent component I pass the function to the child component like this:

<Designer 
  usedComponents={this.state.usedComponents}
  myRef={this.getElem}
/>

Inside the Designer component I map the main area components and pass the ref to them like this:

const components = props.usedComponents.map((component, index) => {
  return (
    <div onMouseUp={() => props.selectComponent(index)} key={index}>
      <DesignerComponent {...component} myRef={props.myRef} />
    </div>
  );
});
return components;

DesignerComponent component is determined through switch statement because each has a different set of props, but inside the switch statement I also pass myRef={props.myRef} to each individual component and then I set the ref inside each individual component like this:

<section ref={props.myRef}></section>

However, this breaks my app and gives me this error message:

"TypeError: Cannot set property 'myRef' of undefined".

What am I doing wrong?

Upvotes: 1

Views: 694

Answers (1)

Goran Tesic
Goran Tesic

Reputation: 739

I figured it out. The function getElem(ref) doesn't seem to do anything. I simply passed myRef={this.myRef} to the Designer component and now it works.

Upvotes: 1

Related Questions