D
D
Denis2018-07-10 11:08:53
React
Denis, 2018-07-10 11:08:53

Forward Ref not working?

Good evening. Please help me figure out why when passing ref through HOC using forwardRef, I get null, when outputting this.documentRef to the console

@connect(
    state => ({
        // code...
    }),
    {
        requestDocuments: someRequests
    }
)

export class MyComponent extends React.Component  {
// Code...

render() {
        return (
                <Grid ref={this.props.forwardRef} />
        );
    }
}

High Order Component:
import React, {forwardRef} from 'react';
import {MyComponent } from './container';

export const MyComponentHOC = React.forwardRef((props, ref) => (
    <MyComponent {...props} forwardRef={ref} />
));

OutSide Call:
import {MyComponentHOC} from './';

class StatefullMyComponentHOC extends React.Component {
    state = {};

    handleClick = (event) => {
        console.log(this.documentRef);
    };

    documentRef = createRef();
 
    render() {
        return (
            <Fragment>
                <StatefullMyComponentHOC ref={this.documentRef}  />
                <button id="4" onClick={this.handleClick}>Обновить контейнер</button>
            </Fragment>
        );
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-07-10
@den0820

Or rewrite Grid to forwardRef, similar to the example:

const Grid = React.forwardRef((props, ref) => (
  <div ref={ref}>{props.children}</div>
));

Either fix:
export class MyComponent extends React.Component {
  render() {
    return (
      <Grid innerRef={this.props.forwardRef} />
    );
  }
}

and in the Grid component:
const Grid = props => (
  <div ref={props.innerRef}>{props.children}</div>
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question