A
A
Artur Kudashev2019-04-25 13:36:06
JavaScript
Artur Kudashev, 2019-04-25 13:36:06

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 />
        )
    }
}

child.js
import React, { Component } from 'react';

childRef = React.createRef();

export default class Child extends Component {
    render() {
        return (
            <div ref = { this.childRef }></div>
        )
    }
}

How do I pass the ref of a child element to the parent?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-25
@archi_kud

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 question

Ask a Question

731 491 924 answers to any question