-1

So I am following some React tutorials and the lecturer is trying to explain forward API's and ref API's.

So we have a children which looks like this

import React, { Component } from 'react';

class Cppersons extends Component {

 myFocus () {
 this.lastref.current.focus() 
 }

 render() {

 //something

 return (

 <div> Something </div>

   )
  }
}
export default Cppersons;

Note: this in above code

myFocus () {
    this.lastref.current.focus() 
    }

In the above code, we created this.lastref first on the parent component hence I think it is coming from there (passing a ref from parent to child) Here is parent component

import React, { Component } from 'react';
import Person from './persons/person-s';

class Cpersons extends Component {
this.lastref = React.createRef()

  componentDidMount() {
this.lastref.current.myFocus()
}

render (
return {
<Person
        key={el.id}
        click={this.props.cpdelete.bind(index)}
        ref={this.lastref}
        name={el.name}
        age={el.age}
        changed={(event) => this.props.cpchanged(event, el.id)} />
      });
    }
  }

export default Cpersons

So my question is that how can we use myFocus in the parent when the method is defined in the children? plus how does myFocus work here?

1 Answers1

1

As DOC says. The value of the ref differs depending on the type of the node:

  • When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property.
  • When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.

So said that and by looking at your code you are using the ref in your custom class component , that means this.lastref.current is an instance of Person. In your case you are calling this.lastref.current.myFocus(). I expect that you have defined the myFocus method within the class Person. Having that ref on Person means you can call any methods you have defined within the Person Component.

  • What do you mean when you say ***mounted instance of the component as its current.***? –  May 07 '18 at 11:24
  • I mean in your case that this.lastref.current is your Person Custom Component. So you can have access to all the methods defined within the Person class. – Antonio Pangallo May 07 '18 at 12:00