Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Access parent component name

Tags:

reactjs

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.

like image 832
Gayan Charith Avatar asked Nov 02 '15 09:11

Gayan Charith


People also ask

How do you call parent component to child component?

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.

What is parent component in react JS?

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.


1 Answers

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).

like image 159
Joshua Robinson Avatar answered Nov 14 '22 22:11

Joshua Robinson