I want to get the parent component name inside the child component to display a error message when validating properties of that child component. I'm creating a reusable component, so anyone can use my component inside their components. When they are using my component I want to display warning messages with the name of the parent component.
Is there a specific method to get parent name in react. Any kind of help would be appreciated.
Call Child Component method from Parent Component A ViewChild is a decorator which is used when we want to access a child component inside the parent component, we use the decorator @ViewChild() in Angular.
A component is a function (or class with a render method) that returns react elements. I would consider any component that's rendered by another component to be a child, and the rendering component to be a parent.
Children can see the context they are composed in through:
this._reactInternalInstance._currentElement._owner._instance.__proto__.constructor.name
For example:
import React, { Component } from 'react';
class Warning extends Component {
render() {
return (
<div>{
"WARNING: " + this._reactInternalInstance._currentElement._owner._instance.__proto__.constructor.name + " has an error."
}</div>
);
}
}
export default Warning;
Do not believe this is parent-child communication. It is like standing in a room and seeing the containing walls from where you are. This is not the container (parent) communicating to you (child) but rather the child being context-aware.
Use this if you must, however, do note that it is part of React's internal instance and subject to change (do believe it is stable enough as of today).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With