Reputation: 932
I need to access 'GreatGrandChild' component in the 'View' component.
<View>
<Child>
....
</Child>
</View>
<Child>
<GrandChild>
....
</GrandChild>
</Child>
<GrandChild>
<GreatGrandChild>
....
</GreatGrandChild>
</GrandChild>
<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?
Upvotes: 1
Views: 2977
Reputation: 132
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>
Upvotes: 0
Reputation: 36179
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.
Upvotes: 3