C
C
Cyril2020-07-26 22:05:02
Web development
Cyril, 2020-07-26 22:05:02

Why in production React in ref.current returns a DOM element and not an object?

There is a certain component "A", like this:

class ComponentA extends React.Component {

  someMethod = () => {
    console.log('test');
  };

  render() {
    return (
      <div className="component-a" ref={this.props.forwardedRef}>
         ...
      </div>
    );
  }
}

export default React.forwardRef((props, ref) => {
  return <ComponentA {...props} forwardedRef={ref} />;
});


And there is a component "B", which, by reference, calls the methods of component "A":

import ComponentA from "./ComponentA";

class ComponentB extends React.Component {

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

  render() {
    return (
      <div className="component-b">
        <ComponentA  ref={this.someRef} />
        <button onClick={() => this.someRef.current.someMethod()}>Click!</button>
      </div>
    );
  }
}


Everything is simple here. We click on the button, and the someMethod() method of component "A" should be called. When I develop locally, everything works, the someMethod() method is called. But when I upload it to production, when the button is pressed, the component starts to give an error:
this.someRef.current.someMethod is not a function

The strange thing is that in production, for some reason, a DOM node () appears in this.someRef.current , and not an object. Although in my local Dev there is an object inside this.someRef.current ...

Please help me figure out why this is so

And due to the fact that in the Production DOM node, it is not possible to call the someMethod() method

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vItalIyIrtlach, 2020-07-26
@w13vitaliy

Since a ref is a reference DOM element and it has properties and methods .
PS Read more about refs in the documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question