1

I need to access 'GreatGrandChild' component in the 'View' component.

View Component:

<View>
  <Child>
    ....
  </Child>
</View>

Child Component:

<Child>
  <GrandChild>
      ....      
    </GrandChild>
</Child>

GrandChild component:

<GrandChild>
  <GreatGrandChild>
    ....
  </GreatGrandChild>
</GrandChild>

GreatGrandChild component:

<GreatGrandChild ref={(component) => { this.component = component; }}>
  ....
</GreatGrandChild>

How do I access the 'GreatGrandChild' component in the 'View' component? Can I access it using refs? Which lifecycle method would be most appropriate in that case?

Sunny
  • 902
  • 3
  • 18
  • 41

2 Answers2

3

You can use a regular prop to pass your ref - but it must have a different name:

// somewhere in constructor
this.greatGrandChild = React.createRef();

<View>
  <Child greatGrandChildRef={this.greatGrandChild}>
    ....
  </Child>
</View>


<Child>
  <GrandChild greatGrandChildRef={this.props.greatGrandChildRef}>
      ....      
    </GrandChild>
</Child>


<GrandChild>
  <GreatGrandChild greatGrandChildRef={this.props.greatGrandChildRef}>
    ....
  </GreatGrandChild>
</GrandChild>

<GreatGrandChild ref={this.props.greatGrandChildRef}>
  ....
</GreatGrandChild>

This is very much the same idea of innerRef in styled-components and how they suggest it in React docs.

Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
0

you can also emit from child to parent on each component and if you need to check something from view in the greatgrandchild, you can do like this:

_____in view :

methods: {

updateValue(valueFromDown){

//you have access to the value from greatgranchild, it is valueFromDown 

...

},

<Child :valueToSend="valueToSend" @updateValue='updateValue'>
    ....
</Child>

______in the child :

props : [ 'valueToSend',...

methods:{

     updateValue(value){
        this.$emit('updateValue', value);
    }
  },

<GrandChild :valueToSend="valueToSend" @updateValue='updateValue'>
      ....      
</GrandChild>

_____in the granchild:

props : [ 'valueToSend', ...

methods:{

    updateValue(value){

        this.$emit('updateValue', value);
    }
  },

<GreatGrandChild :valueToSend="valueToSend" @updateValue='updateValue'>
      ....      
</GreatGrandChild>

_____and in the GreatGrandChild :

props : [ 'valueToSend',...

methods:{

checkTheValue(){

//check...

this.$emit( 'updateValue', valueFromDown); // i think it is your this.component

}

<GreatGrandChild ref={(component) => { this.component = component; }}>
  ....
</GreatGrandChild>
alex
  • 132
  • 4