Answer the question
In order to leave comments, you need to log in
How to pass ref to parent component?
Hello, I read in the documentation about passing a ref from a child component to a parent using React.forwardRef(), but the examples use functions, and I need classes.
Parent.js
import React, { Component } from 'react';
import Child from './Child';
class Parent extends Component {
render() {
return (
<Child />
)
}
}
import React, { Component } from 'react';
childRef = React.createRef();
export default class Child extends Component {
render() {
return (
<div ref = { this.childRef }></div>
)
}
}
Answer the question
In order to leave comments, you need to log in
import React, { Component } from 'react';
import Child from './Child';
class Parent extends Component {
childRef = React.createRef();
render() {
return (
<Child innerRef={this.childRef} />
);
}
}
import React, { Component } from 'react';
export default class Child extends Component {
render() {
const { innerRef } = this.props;
return (
<div ref={innerRef}></div>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question